簡體   English   中英

需要幫助重構簡單的jquery動畫腳本

[英]Need help refactoring a simple jquery animation script

我的狀態消息框(div框)位於網頁底部,位置為:固定; 和底部:0;。 最初的高度為11px。

我想允許用戶在狀態消息超出默認高度的情況下雙擊它,使其增長。 如果他們再次雙擊它或將鼠標移離該框,則它應再次縮小。

我設法完全按照我的意願進行工作,但是在我看來,應該可以更優雅地編寫此代碼:

<script type="text/javascript">
    $(document).ready(function() {
        $("#footer").dblclick(showStatusBar);
    });     
    function showStatusBar() {
        var footer = $("#footer");
        footer.unbind('dblclick', showStatusBar);
        footer.animate({ height: "100px" }, 200);
        footer.dblclick(hideStatusBar);
        footer.bind('mouseleave', hideStatusBar);
    }

    function hideStatusBar() {
        var footer = $("#footer");
        footer.unbind('mouseleave', hideStatusBar);
        footer.unbind('dblclick', hideStatusBar);
        footer.animate({ height: "11px" }, 200);            
        footer.dblclick(showStatusBar);
    }
</script> 

我玩過切換事件,但無法正常工作。

您可以創建一個充當切換功能的功能。 像這樣:

// NOTE: Untested!
function statusBarToggle() {
    /* Starts as hidden. */
    if(this.isHidden == undefined)
        this.isHidden = true;

    this.isHidden = !this.isHidden;

    var newHeight = this.isHidden ? 11 : 200;

    $(this)
        .stop()
        .animate({ height: newHeight + 'px' }, 200);

    /* When mouse leaves open status bar, close it. */
    if(this.isHidden)
        $(this).unbind('mouseleave', statusBarToggle);
    else
        $(this).bind('mouseleave', statusBarToggle);
}

$(document).ready(function() {
    // ...
    $('#footer').dblclick(statusBarToggle);
}

這為狀態欄提供了“ isHidden”屬性,並使用它來檢查我們是否顯示或隱藏狀態欄。 如果需要,此功能還可與其他元素一起使用。

(就像我上面用“停止”和“動畫”功能所做的那樣,您可以鏈接許多jQuery命令。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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