开发者

Animate absolutely positioned div, but stop if a condition is true?

I have a div which I place at the top right-hand corner of a website, absolutely positioned at top: 0px and right : 0px. I want to use jquery's animate function to animate the div left or right a certain amount when a but开发者_高级运维ton is clicked, but stop the animation if at anytime, the div's offset to the left or right is less than a certain number. I want to do this to accomodate users who click the left or right buttons more than once, so that the div does not fly out of sight. How does one accomplish this? Below is my relevant css, html, and jquery code:

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 (at the moment):

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


One way is to remove the event listener on the buttons when clicked once, so the user can't click again:

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

Another way would be to check the location on each step:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜