jQuery:在滚动上移动元素,在某处停止,跨浏览器兼容

jQuery : move an element on scroll, stop at some point, cross-browser compatible

我正在尝试在页面上设置一个固定元素,该元素将跟随内容的其余部分直至用户滚动。

例如,在Internet Explorer上尝试http://jsfiddle.net/sVzfx/1/,您将看到我的问题(在firefox上不会发生,而在歌剧上却有些奇怪)。在这个jsfiddle中,我使用scroll事件和一行代码来定位浮动元素:

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

(为此,请参阅在某个位置停止固定位置滚动吗?)

=>滚动事件发生在内容滚动之后。因此,固定元素会有一些延迟...

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

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

你会怎么做? x(

也许我应该让元素相对并在元素到达页面顶部时将其更改为fixed。因此,在滚动之前就不必移动它了。


在我想到了以相对元素而不是固定元素为基础的想法之后,我想到了这个解决方案。参见http://jsfiddle.net/sVzfx/7/:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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/