使用简单的jquery脚本让div跟随滚动页面 [英] using a simple jquery script to have a div follow the page on scroll

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

问题描述

我正在尝试使用此脚本: http://css-tricks.com/ scrollfollow-sidebar / 在用户滚动时创建一个跟随窗口的简单div。我将它从0更改为topPadding并将topPadding更改为topPadding * 2以获得正确的顶部偏移。

I'm trying to use this script here: http://css-tricks.com/scrollfollow-sidebar/ to make a simple div that follows the window as the user scrolls. I changed it from 0 to topPadding and changed topPadding to topPadding*2 to get the right top offset.

不幸的是,这会产生对象的副作用,使页面变得有点更长,并允许用户无限滚动。如果你让窗口足够小,这个bug实际上也在原始代码中没有我更大的toppadding更改。

Unfortunately this has the side effect of the object making the page a little longer and allowing the user to scroll infinitely. This bug is also actually in the original code without my larger toppadding changes if you make the window small enough.

我还尝试了另一个jquery插件,但它没有工作,这给了我我需要的东西,所以我该怎么办呢?

I also tried another plugin for jquery, but it didn't work at all and this gives me what I need, so how can I fix it?

推荐答案

我把这个快速拼凑起来修正案,根据文件高度进行限制。我不确定jQuery是否给出了准确的高度,因此安全屏障为100px。即使高度不是很正确,任何额外的滚动都会受到限制,当然也不会无限。

I've knocked together this quick amendment, which limits based on the document height. I'm not certain that jQuery is giving an accurate height, hence a safety barrier of 100px. Even if the height isn't quite right, any extra scrolling will be limited and certainly not infinite.

<script type="text/javascript">
    var documentHeight = 0;
    var topPadding = 15;
    $(function() {
        var offset = $("#sidebar").offset();
        documentHeight = $(document).height();
        $(window).scroll(function() {
            var sideBarHeight = $("#sidebar").height();
            if ($(window).scrollTop() > offset.top) {
                var newPosition = ($(window).scrollTop() - offset.top) + topPadding;
                var maxPosition = documentHeight - (sideBarHeight + 100);
                if (newPosition > maxPosition) {
                    newPosition = maxPosition;
                }
                $("#sidebar").stop().animate({
                    marginTop: newPosition
                });
            } else {
                $("#sidebar").stop().animate({
                    marginTop: 0
                });
            };
        });
    });
</script>

这篇关于使用简单的jquery脚本让div跟随滚动页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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