簡體   English   中英

單擊鏈接時,如何切換DIV的大小以擴展其高度?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM