代码之家  ›  专栏  ›  技术社区  ›  Alex

动画绝对定位的DIV,但如果条件为真停止?

  •  2
  • Alex  · 技术社区  · 14 年前

    我在网站右上角有一个分区,绝对位于 top: 0px right : 0px . 我想使用jquery的animate函数在单击某个按钮时左右移动某个数字,但如果在任何时候,该数字向左或向右的偏移量小于某个数字,则停止动画。我想这样做是为了满足用户谁点击左或右按钮一次以上,这样的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?
        }); 
    
    1 回复  |  直到 14 年前
        1
  •  2
  •   David Hellsing    14 年前

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

    $("#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();
                }
            }
        });
    });