2013-03-06 44 views
1

我试图在页面上有一个固定的元素,当用户滚动时,它会跟随内容的其余部分。jQuery:在滚动上移动元素,在某个点停止,跨浏览器兼容

尝试在Internet Explorer上的http://jsfiddle.net/sVzfx/1/例如,你会看到我的问题(这不会发生在Firefox上,只是做一些少奇怪的歌剧)。在此的jsfiddle我使用滚动事件和一行代码到浮动元件的位置是:

$(window).scroll(function() { 
    $("#floatingContent").css("top", Math.max(maxTopPosition, startingPoint - $(this).scrollTop())); 
}); 

(参见Stopping fixed position scrolling at a certain point?此)

=>滚动事件发生的内容已滚动后。因此,固定元件会延迟一段时间...

为了获得最佳的用户体验,至关重要的是不存在这样的行为。我的想法是计算滚动的的像素数量,在滚动其余内容之前放置元素。用户不会看到这个元素位于其他元素之前,因为它太快了,我想。问题是,我该怎么做?!

我试过使用鼠标滚轮插件(请参阅http://brandonaaron.net/code/mousewheel/docs)。它使我能够在实际滚动之前做些事情,而不是确定滚动像素的数量......(我认为deltaY参数会返回,但它不会)。

你会怎么做? X(

也许我应该让元素相对并将其更改为固定的,一旦它到达页面的顶部...因此忘掉滚动前移动它。

回答

1

我后,我想出了这个解决方案得到具有作为基础的,而不是一个固定元件的相对元件的想法参见http://jsfiddle.net/sVzfx/7/

var fixedElement = false; 
var changingMoment = 250; // numbers of pixels from top where we want to fix or unfix 
$(window).scroll(function() { 
    // floatingContentMark lets us know where the element shall change 
    // from fixed to relative and vice versa 
    var distanceFromTop = $("#floatingContentMark").offset().top - $(this).scrollTop();  
    if ((distanceFromTop <= changingMoment && !fixedElement) || 
     (distanceFromTop >= changingMoment && fixedElement)) 
    { // either we came from top or bottom, same event triggered 
     fixedElement = !fixedElement; 
     $('#floatingContent').trigger('fixElement'); 
    } 
}); 

// maybe dispatch in two different handlers, fix and unfix. 
$('#floatingContent').bind('fixElement', function() { 
    if ($(this).css('position') != 'fixed') { 
     $(this).css('position', 'fixed') ; 
     $(this).css('top', changingMoment) ; 
    } 
    else { 
     $(this).css('position', 'relative') ; 
     $(this).css('top', 'auto') ; 
    } 
}) ; 

另一种解决方案可以是http://imakewebthings.com/jquery-waypoints/shortcuts/sticky-elements/

相关问题