需要帮助重构一个简单的jquery动画脚本

时间:2008-11-27 23:54:28

标签: javascript jquery refactoring

我的状态消息框(div框)位于网页底部,位置为:fixed;和底部:0;。它的高度最初为11px。

我想允许用户在状态消息多于默认高度范围内时双击它,使其增长。如果他们再次双击它或将鼠标从盒子中移开,它应该再次收缩。

我对javascript和jquery完全不熟悉,所以对我来说很陌生。我设法让这个工作完全按照我的意愿运行,但在我看来应该可以更优雅地写出来:

<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> 

我参加了toggle活动,但无法让它发挥作用。输入将非常感激。

最好的问候,埃吉尔。

1 个答案:

答案 0 :(得分:5)

您可以创建一个充当切换功能的功能。像这样:

// 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命令,正如我上面用'stop'和'animate'函数做的那样。)

相关问题