我可以用不同的按钮来做这个功能。但我不能通过点击相同的按钮来实现这一点。点击显示'Div 1'并隐藏'Div 2'&点击同样的按钮显示'Div 2'并隐藏'Div 1'?
使用ternary-operator
Element.style.display
任何帮助/建议 感谢
我可以用不同的按钮来做这个功能。但我不能通过点击相同的按钮来实现这一点。点击显示'Div 1'并隐藏'Div 2'&点击同样的按钮显示'Div 2'并隐藏'Div 1'?
使用ternary-operator
Element.style.display
任何帮助/建议 感谢
display
CSS 财产var btn = document.getElementById('btn');
var curr = 'div2';
btn.onclick = function() {
document.getElementById(curr).style.display = 'none';
curr = curr === 'div2' ? 'div1' : 'div2';
document.getElementById(curr).style.display = 'block';
};
div {
display: none;
}
<div id="div1">#div1</div>
<div id="div2">#div2</div>
<button id='btn'>Change</button>
任何这样的事情?
function divchange(){
div1 = document.getElementById("div1");
div2 = document.getElementById("div2");
if(div1.style.display == "none"){
div1.style.display = "block";
div2.style.display = "none";
}else{
div1.style.display = "none";
div2.style.display = "block";
}
}
<button id="divchangebutton" onclick="divchange();">test</button>
<div id="div1">asdf</div>
<div id="div2" style="display:none;">qwert</div>
问题 - 如果 “显示:无” 套在CSS中,我们不能得到的价值。 “elem.style.display”返回空字符串。 我们可以使用Computed Style来解决这个问题。
var btn = document.getElementById("btn-toggle");
btn.addEventListener("click", function(){
var one = document.querySelector(".one");
var tow = document.querySelector(".tow");
one.style.display = (getRealDisplay(one) == 'none') ? 'block' : 'none';
tow.style.display = (getRealDisplay(tow) == 'none') ? 'block' : 'none';
});
// get real value of 'display' property
function getRealDisplay(elem) {
if (elem.currentStyle) {
return elem.currentStyle.display;
} else if (window.getComputedStyle) {
var computedStyle = window.getComputedStyle(elem, null);
return computedStyle.getPropertyValue('display');
}
}
.one, .tow{
width:200px;
min-height: 200px;
background-color:burlywood;
}
.tow{
display: none;
background-color:cadetblue;
}
<div class="one">1</div>
<div class="tow">2</div>
<button id="btn-toggle">show hide</button>
可以知道在哪个语言,你在做这个? –
请使用您的代码更新您的问题并正确解释 –
将代码放在代码中没有人可以帮助您 – mean