一旦到达另一个div,就停止div滚动 [英] Stop div scrolling once it reaches another div

查看:799
本文介绍了一旦到达另一个div,就停止div滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我当前有一个div保持固定并跟随用户滚动直到达到某一点。我可以很容易地让它停在一个固定的像素位置,就像我在下面的例子中所做的那样,但是因为我是一个jQuery白痴我不知道如何让它停在一个div而不是。

Basically I currently have a div which stays fixed and follows the user down as they scroll until it reaches a certain point. I can easily make it stop at a fixed pixel position as I have done in the below example, but because I'm a jQuery idiot I have no idea how to make it stop at a div instead.

这是我到目前为止所使用的:

Here's what I've used so far:

var windw = this;

$.fn.followTo = function ( pos ) {
     var $this = this,
        $window = $(windw);

$window.scroll(function(e){
    if ($window.scrollTop() > pos) {
        $this.css({
            position: 'absolute',
            top: pos
        });
    } else {
        $this.css({
            position: 'fixed',
            top: 0
        });
    }
});
};

$('#one').followTo(400);

以下是示例: jsFiddle

我希望它一旦到达第二个div就停止的原因是因为我正在使用流畅的布局,第二个div将根据浏览器大小坐在不同的点。为它停止定义一个特定的点将不起作用。任何人都有任何想法,我怎么能得到这样做我想要的?或者,固定div是否可以在达到一定百分比时停止滚动?我环顾四周但没找到任何东西。

The reason I want it to stop once it reaches a second div is because with the fluid layout I'm using, the second div will be sitting at different points depending on the browser size. Defining a specific point for it to stop at won't work. Anyone got any ideas as to how I can get this to do what I want? Alternatively, is it possible for the fixed div to stop scrolling once it reaches a percentage of the way down? I've looked around but haven't found anything.

感谢您的帮助。

推荐答案

这是你要找的吗?

http://jsfiddle.net/Tgm6Y/1447/

var windw = this;

$.fn.followTo = function ( elem ) {
    var $this = this,
        $window = $(windw),
        $bumper = $(elem),
        bumperPos = $bumper.offset().top,
        thisHeight = $this.outerHeight(),
        setPosition = function(){
            if ($window.scrollTop() > (bumperPos - thisHeight)) {
                $this.css({
                    position: 'absolute',
                    top: (bumperPos - thisHeight)
                });
            } else {
                $this.css({
                    position: 'fixed',
                    top: 0
                });
            }
        };
    $window.resize(function()
    {
        bumperPos = pos.offset().top;
        thisHeight = $this.outerHeight();
        setPosition();
    });
    $window.scroll(setPosition);
    setPosition();
};

$('#one').followTo('#two');

编辑:关于你要求在某个点之前不滚动的请求,只需替换它:

about your request to not scroll until a certain point, just replace this:

if ($window.scrollTop() > (bumperPos - thisHeight)) {

这个:

if ($window.scrollTop() <= (bumperPos - thisHeight)) {

这篇关于一旦到达另一个div,就停止div滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆