[英]How do I toggle the size of a DIV to extend its height when a link is clicked?
我正在尝试扩展“顶部栏”以显示一系列链接。
为此,我选择了jQuery,一些研究表明我应该对此进行切换。
在处理“顶部栏”类的许多失败事件之后,我尝试了一种不同的方法-请参阅: http : //jsfiddle.net/SQHQ2/2408/
HTML:
<div id='topbar'>toggle me</div>
<a href="#" class="menu">Toggle</a>
CSS:
#topbar {
background: orange;
color: white;
height: 60px;
text-align:center;
}
jQuery:
$(".menu").click(function() {
$("#topbar").toggle(function() {
$("#topbar").animate({
height: 165
}, 200);
}, function() {
$("#topbar").animate({
height: 60
}, 200);
});
});
当我尝试此代码时,它只是以动画方式隐藏了顶部栏。
您能否帮助我实现一个解决方案,只需单击类“ .menu”的链接,即可将“顶部栏” DIV从60px的高度扩展到160px的高度,以显示隐藏的链接?
我欢迎通过其他方式获得的解决方案,只要它们可行:)
祝新年和TIA一切顺利。
要考虑的另一种方法是将所有CSS和JavaScript分开。 这是我的意思的示例:
HTML
<div id='topbar'>toggle me</div>
<a href="#" class="menu">Toggle</a>
CSS
#topbar {
background: orange;
color: white;
text-align:center;
}
.short {
height: 60px;
}
.tall {
height: 160px;
}
JavaScript的
$(".menu").click(function() {
$('#topbar').toggleClass('short', 'tall');
});
想法是将样式保留在CSS中,然后切换要应用的类。
.toggle
是jQuery中的处理程序,可在点击时切换(这就是为什么您的栏在单击时切换的原因)
$(".menu").toggle(function() {
$("#topbar").animate({
height: 165
}, 200);
}, function() {
$("#topbar").animate({
height: 60
}, 200);
});
应该工作正常。
$(".menu").toggle(function() {
$("#topbar").animate({
height: 165
}, 200);
}, function() {
$("#topbar").animate({
height: 60
}, 200);
});
也许您可以在标签中添加属性以保持状态(展开/未展开)。 而不是切换,而是使用它来设置顶部栏的动画
HTML
<div id='topbar'>toggle me</div>
<a expanded="0" href="javascript:void(0);" class="menu">Toggle</a>
JS
$(".menu").click(function() {
var thisObj = this;
var expanded = parseInt($(thisObj).attr("expanded"));
if (expanded){
$("#topbar").animate({height:60},200, function(){
$(thisObj).attr("expanded", "0");
});
} else {
$("#topbar").animate({height:160},200, function(){
$(thisObj).attr("expanded", "1");
});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.