Jquery跟随滚动 [英] Jquery follow scroll

查看:63
本文介绍了Jquery跟随滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站上有一种侧边栏,它必须与用户一起向下滚动,以便它始终在视图中。

I have a sort of sidebar on my website, which has to scroll down together with the user so that it is always in the view.

我现在使用的代码实际上工作正常,但有一个问题。在较小的屏幕上,侧边栏会在侧边栏之前滚动,因此即使您滚动也无法看到它。

The code I'm using now is actually working fine however there is one problem. On smaller screens the sidebar scrolls before your at the sidebar thus making it impossible to see it all even if you scroll.

所以我想要的是边栏滚动底部而不是顶部向下推,这样当你到达侧边栏的末尾就会开始滚动。

So what I want is the sidebar to scroll with the bottom instead of it being pushed down with the top so that when you reach the end of the sidebar it starts to scroll.

这是我目前正在使用的代码。

This is the code that I'm currently using.

var documentHeight = 0;
var topPadding = 10;
$(function() {
    var offset = $("#mainright").offset();
    documentHeight = $(document).height();
    $(window).scroll(function() {
        var sideBarHeight = $("#mainright").height();
        if ($(window).scrollTop() > offset.top) {
            var newPosition = ($(window).scrollTop() - offset.top) + topPadding;
            var maxPosition = documentHeight - (sideBarHeight);
            if (newPosition > maxPosition) {
                newPosition = maxPosition;
            }
            $("#mainright").stop().animate({
                marginTop: newPosition
            });
        } else {
            $("#mainright").stop().animate({
                marginTop: 0
            });
        };
    });
});

推荐答案

我认为完成这样的任务的最佳实践是使用动态变化的css位置从绝对已修复,反之亦然。基本示例如下:

I guess the "best practice" for accomplishing a task like this is to use dynamically changing css position from absolute to fixed and vice versa. A basic example could look like:

$(function(){
   var $box    = $('.box'),
       offset  = $box.offset(),
       doc_h   = $(document).height();

    $(window).scroll(function(){
        if($(window).scrollTop() > offset.top) {
            if(!$box.hasClass('fix'))
                $box.toggleClass('normal fix');
        }
        else{
            if(!$box.hasClass('normal'))
                $box.toggleClass('normal fix');
        }
    });
});​

行动中的示例:< a href =http://www.jsfiddle.net/YjC6y/14/ =nofollow> http://www.jsfiddle.net/YjC6y/14/

这篇关于Jquery跟随滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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