开发者

Do something if position is less than X. Jquery

开发者_如何学C$("#rightControl").click(function(){
    $("#thumb_menu").animate({"left": "-=520px"}, "slow");
    var pos = $('#thumb_menu').position();
    if(pos.left < 0) { 
        $('#header')
            .prepend('<span class="control" id="leftControl">Move left</span>')
}
});

Clicking #rightControl once moves #thumb_menu to -450px left so the if should run but I cant seem to get this working.

Where am I going wrong?


Place it in a callback to the .animate() so that it has a chance to change its position before the .position() method is invoked..

$("#rightControl").click(function () {
    $("#thumb_menu").animate({
        "left": "-=520px"
    }, "slow", function() {
        var pos = $(this).position();
        if (pos.left < 0) {
            $('#header').prepend('<span class="control" id="leftControl">Move left</span>')
        }
    });
});

Although if you know it is moving to a negative position, I wouldn't think you'd need the if() statement at all. Just do the .prepend() in the callback.


The position method is relative to the document, not the element's original position: http://api.jquery.com/position/

So .position() will only be < 0 if the element is actually off the screen. What you should do is capture the original position of the element before you move it and then see if it's less than that.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜