当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - using a simple jquery script to have a div follow the page on scroll

问题描述:

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.

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.

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?

网友答案:

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>
网友答案:

Why not just use CSS.

#theNonMovingDiv {position:absolute; position: fixed; top: Npx; right:Mpx}

position:fixed; doesn't work in ie6, but including the position:absolute; will give you a rough approximation.

网友答案:

I can duplicate your bug in my browser (Firefox 3.5).

The problem is that the code doesn't look to see if the bottom of the sidebar falls off the end of the document.

Your best bet is to use the .height() method to check. You can get the height of the sidebar (as presented in the example) as $("#sidebar").height(), and the height of the whole document as $(document).height().

What exactly the behavior should be -- up to you. It involves an extra if, to make sure all your pixels line up right, but design questions, like how the sidebar should align against the bottom, are going to be a matter of personal taste.

分享给朋友:
您可能感兴趣的文章:
随机阅读: