单击链接时,如何切换 DIV 的大小以扩展其高度

How do I toggle the size of a DIV to extend its height when a link is clicked?

本文关键字:扩展 高度 DIV 链接 何切换 单击      更新时间:2023-09-26

我正在尝试使"顶部栏"扩展以显示一系列链接。

为此,我选择了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");  
        });
    }
});