【问题标题】:Animate absolutely positioned div, but stop if a condition is true?动画绝对定位的div,但如果条件为真则停止?
【发布时间】:2011-03-03 04:18:45
【问题描述】:

我有一个 div 放在网站的右上角,绝对位于 top: 0pxright : 0px。我想使用 jquery 的 animate 函数在单击按钮时将 div 向左或向右设置一定量的动画,但如果在任何时候,div 向左或向右的偏移量小于某个数字,则停止动画。我想这样做是为了容纳多次单击向左或向右按​​钮的用户,这样 div 就不会飞出视线。如何做到这一点?下面是我的相关css、html和jquery代码:

CSS:

  #scorecardTwo {
    position:absolute;
      padding:5px;
      width: 300px;
      background-color:#E1E1E1;
      right:0px;
      top:0px;
      display:none;
  }

HTML:

        <div id = "scorecardTwo"> 
            <span id = "dealHolder"><a href="some/link">some text</a></span>
            <br />
            <span id = "scoreHolder">some text</span>
            <br />
            <button type="button" id="moveLeft">Left</button>&nbsp;<button type="button" id="moveRight">Right</button>
        </div>

jQuery(目前):

    $("#scorecardTwo").fadeIn("slow");

    $("#moveLeft").bind("click", function() {
            $("#scorecardTwo").animate({"right":"+=76%"}, "slow");
                            // how to stop animation if offset is less than appropriate number?
    });

    $("#moveRight").bind("click", function() {
            $("#scorecardTwo").animate({"right" : "-=76%"}, "slow");
                            // how to stop animation if offset is less than appropriate number?
    }); 

【问题讨论】:

    标签: jquery jquery-animate


    【解决方案1】:

    一种方法是在单击一次时删除按钮上的事件侦听器,这样用户就不能再次单击:

    $("#moveLeft").bind("click", function() {
        $("#scorecardTwo").animate({"right":"+=76%"}, "slow");
        $(this).unbind('click', arguments.callee);
    });
    

    另一种方法是检查每个步骤的位置:

    $("#moveLeft").bind("click", function() {
        $("#scorecardTwo").animate({"right":"+=76%"}, {
            speed: "slow",
            step: function(right) {
                if (right >= 70) { // stop at ~70
                    $("#scorecardTwo").stop();
                }
            }
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 2020-09-29
      • 2012-09-03
      相关资源
      最近更新 更多