【问题标题】:Need help refactoring a simple jquery animation script需要帮助重构一个简单的 jquery 动画脚本
【发布时间】:2008-11-27 23:54:27
【问题描述】:

我有一个状态消息框(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> 

我尝试了toggle 事件,但无法使其正常工作。

【问题讨论】:

  • 顺便说一句,您可能需要重新考虑使用 DOUBLEclick 事件。不看界面就很难判断,但在网页和应用程序中使用双击的情况非常少见,因此人们可能没有预料到或意识到在您的应用程序中它是可能的。
  • 我同意@Daan:网络是以单击为中心的。按钮、链接和输入焦点都使用单击。切换应该以相同的方式工作。

标签: javascript jquery refactoring


【解决方案1】:

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

// 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' 函数所做的那样。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-13
    相关资源
    最近更新 更多