开发者

Different behaviour for jQuery animate function in Mozilla and Chrome

开发者 https://www.devze.com 2023-03-20 15:25 出处:网络
I can\'t figure out why this code behaves开发者_StackOverflow中文版 differently in Mozilla and Chrome.

I can't figure out why this code behaves开发者_StackOverflow中文版 differently in Mozilla and Chrome.

The second click function works correctly in both Gecko and WebKit, but the first, instead of decrementing the offset by -165px, offsets by a larger amount in WebKit.

If any details would help or if it's difficult to know without more code, let me know.

$('#pager-next-nav').click( function() {
    if ($('#pager').offset().left < 376 && $('#pager').offset().left > -270) {
        $('#pager').animate( { left: '-=165' }, 1000 );
        $(this).css( { 'cursor': 'pointer', 'color': '#FFF' } );
    }
    else $(this).css( { 'cursor': 'default', 'color': '#CCC' } );
});

$('#pager-prev-nav').click( function() {
    if ($('#pager').offset().left < 300) {
        $('#pager').animate( { left: '+=165' }, 1000 );
    }
});


The issue was/is that Gecko/Trident were converting my percentage-based 'left' css value to pixels before the first increment/decrement but WebKit wasn't. The percentage-based value in WebKit was only happening for the first page load; once it was incremented or decremented, the value would be pixel-based. But since the first value is vastly different depending on whether it's pixel or percentage-based, the decrement amount would be out of whack.

I added a conditional to convert the initial percentage value of 50% (which was relative to a centered div, so was in the center of the document as well), to a pixel value which was half of the document width. The code has changed a lot in the meantime, but the basic issue didn't change (WebKit handled the pixel-based animation of position differently that the other two engines if the initial value was a percentage).

Anyway, here's the solution that ended up working:

var document_width = $(document).width();
var left_pos = $('#pager').css('left');
// if left_pos is a percentage
if (left_pos == '50%') {
    left_pos = (document_width/2) + 'px';
    $('#pager').css('left', left_pos);
}
0

精彩评论

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