[英]How to change style under div with onclick on button
我搜索类似问题已有很长时间了,但所有搜索都徒劳无功。 这是我的代码
<div class="footer-sidebar container" style="height:40px;"></div>
<button class="button">Click</button>
现在,如果有人单击按钮,那么我的.container
高度应增加到400px,如果有人单击同一按钮,则它必须回到40px。
编辑:(添加了CSS)
.footer-sidebar {
position: fixed;
z-index: 1500;
bottom: 0;
left: 0;
right: 0;
margin: 0 auto;
overflow: hidden;
}
谢谢
您可以通过向div中添加一个类来做到这一点,如下所示:
$('.button').on('click', function(){
$('.container').toggleClass('open');
}
为此应避免使用内联样式。 使用您的css文件并向其中添加以下内容:
.container {
height: 40px;
}
.container.open {
height: 400px;
}
JQuery
选项相对): booleans
(已测试):
var fullSize = false; // Used for toggling var button = document.getElementsByClassName("button")[0]; // Get button var div = document.getElementsByClassName("footer-sidebar")[0]; // Get div button.onclick = function() { if(fullSize) { div.style.bottom = 0 + "px"; fullSize = false; } // If div is already 400px... else { div.style.bottom = -360 + "px"; fullSize = true; } // If div is already 40px... };
使用classes
(未经测试):
CSS :
.open { height: 400px; } .closed { height: 40px; }
Javascript :
var button = document.getElementById("button"); // Get button var div = document.getElementsByClassName("footer-sidebar container")[0]; // Get div button.onclick = function() { if(div.className = "closed") { div.className = "open" } else if(div.className = "open") { div.className = "closed" } else { div.className = "open" } }
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.