点击即显示'Div 1'&隐藏'Div 2'&单击同一按钮显示'Di
On click show 'Div 1' & hide 'Div 2' & On click of same button show 'Div 2' and hide '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中设置了"display:none",则无法获取值。"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>
相关文章:
- Onchange没有'不要显示或隐藏Div
- 当DIV中的文本高亮显示时,如何获得DIV中Span的值?(Javascript)
- JavaScript/jQuery:显示DIV,直到用户停止在Textbox中键入
- Div赢得't单击时显示
- 单击javascript按钮显示/隐藏Div元素
- 需要 DIV 显示/隐藏开关在幻灯片切换发生后发生
- 无法让 Div 显示超过某个点
- HTML DIV 显示无元素调整大小
- 将 DIV 显示为叠加层
- 如何使 Dreamweaver AP Div 显示/隐藏功能在 IE9 中工作
- 弹出 Div 显示在按钮悬停上
- 选择所有具有样式的 DIV 显示无
- Div 显示:无 - 只想在内容可见时加载内容
- Div显示至少1秒,或直到加载主要内容(以先到者为准)
- Div显示隐藏失败与引导和wordpress
- 当我使用ID时,Div显示更改为隐藏
- 基于按钮的Div显示
- 基于单选的Div显示
- 如何显示一个固定的Div在底部后面的另一个Div显示像视差滚动
- Div显示/隐藏选项卡类