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

时间:2010-06-13 09:07:13

标签: jquery jquery-animate

我有一个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?
    }); 

1 个答案:

答案 0 :(得分:2)

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

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