1

我在我的侧边栏中使用 jQuery 作为浮动小部件 - 链接到我的帖子http://www.product-investigation.com/fat-loss-factor-review - 如果你向下滚动,你会明白我的意思..我想要在页脚之前在侧边栏中停止我的 adsense 小部件..感谢您的帮助 :)

我的 javascript

<script>
$(document).ready(function() {
        function isScrolledTo(elem) {
            var docViewTop = $(window).scrollTop(); //num of pixels hidden above current screen
            var docViewBottom = docViewTop + $(window).height();
            var elemTop = $(elem).offset().top; //num of pixels above the elem
            var elemBottom = elemTop + $(elem).height();
            return ((elemTop <= docViewTop));
        }
        var catcher = $('#catcher');
        var sticky = $('#sticky');
        $(window).scroll(function() {
            if(isScrolledTo(sticky)) {
                sticky.css('position','fixed');
                sticky.css('top','100px');
            }
            var stopHeight = catcher.offset().top + catcher.height();
            if ( stopHeight > sticky.offset().top) {
                sticky.css('position','absolute');
                sticky.css('top',stopHeight);
            }
        });
    });
    </script> 
4

1 回答 1

3

I've updated your jsfiddle. I changed something in your conditions:

return ((elemTop <= docViewTop || elemTop >= docViewTop)); //Changed your return in isScrolledTo

Explanation: The code that I added below will position the sticky div at the top of the footer, If I use your original return statement and scroll up, the sticky div's position will still be absolute on top of the footer. It's because your return statement will only check if the top position of the element is less or equal to the scrollTop() value, which can only be used during scrolldown. In my case where the sticky is already at the bottom part, the isScrolledTo() should also check if the top of the sticky div is greater or equal to the scrollTop() value.

and added some things in the .scroll()

$(window).scroll(function() {
    if(isScrolledTo(sticky)) {
      sticky.css('position','fixed');
      sticky.css('top','2px');
    }
    var stopHeight = catcher.offset().top + catcher.height();
    var stickyFoot = sticky.offset().top + sticky.height();

    if(stickyFoot > footTop -10){ //Check if sticky's foot passes footer's top
      console.log("Top of Footer");
      sticky.css({
        position:'absolute',
        top: (footTop - 20) - sticky.height()
      });
    } else {
      if ( stopHeight > sticky.offset().top) {
        console.log("Default position");
        sticky.css('position','absolute');
        sticky.css('top',stopHeight);
      }
    }
});

Hope it helps.

于 2013-01-12T03:18:41.453 回答