[英]Toggle height of a div with jquery
我有一个类名为“ content”的div,它具有一些内容。 我将其高度设置为80px。 高度:80px; 溢出:隐藏;
我有一个类名为“按钮”的按钮,我试图切换并使其高度自动,或者在单击时将其高度更改为80像素,然后再次单击将div恢复为80像素。
我还试图让按钮在之间显示更多/更少显示之间更改其值
谢谢
.height {
height: 80px;
}
$(".button").click(function(){
$("div.container").toggleClass("height");
});
这是摆脱许多javascript的解决方案,
$('.button').click(function(){ $('.content').toggleClass('changeHeight'); $('.button > *').toggleClass('show hide') })
.show {display: block;} .hide {display: none;} .content {height: 80px; background: red; color: white;} .content.changeHeight {height: auto;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <div class="content"> <div>Some contents</div> </div> <button class="button"> <span class="show">Show</span> <span class="hide">Hide</span> </button>
如果要为其设置动画,则可以向类content
添加transition
。
还有另一种有用的方式将类切换到包含这两个元素(button和div)的父元素。
检查此代码段。 希望能帮助到你!
$(".btn").on("click", function(){ var $btn = $(".btn"); var $content = $(".content"); $content.toggleClass("sized"); if($btn.text() == "Show More"){ $btn.text("Show Less") } else if($btn.text() == "Show Less"){ $btn.text("Show More") } });
body{ font-family: sans-serif; } .content{ height: 80px; background: #f3f3f3; padding: 5px 10px; box-sizing: border-box; border-radius: 3px; } .btn{ margin-top: 10px; padding: 10px; background: #d63333; display: inline-block; color: #fff; border-radius: 3px; cursor: pointer; } .sized{ height: auto; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="content sized">Hello World!</div> <div class="btn">Show More</div>
这可以为您提供帮助
$(document).ready(function (){
$("#button").on("click", function (){
if ($(".content").height() == 0) {
$(".content").animate(
{height: "80px"});
}
else if ($(".content").height() == 80) {
$(".content").animate({height: "0px"});
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.