Jquery follow scroll

南笙酒味 提交于 2020-01-13 18:53:15

问题


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
            });
        };
    });
});


回答1:


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');
        }
    });
});​

Example in action: http://www.jsfiddle.net/YjC6y/14/




回答2:


$(function() {
  var top = 50;
  $(window).scroll(function() {
    $('#box').stop().animate({ top: $(window).scrollTop() + top}, 1000);
  });
});

Try the example : http://jsbin.com/omiyi3




回答3:


I think you can instead make the sidebar responsive by throwing your function into one of these:

if (responsive_viewport >= 768) {}

This makes it so that the function will only load if the viewport is bigger than or equal to 768px.



来源:https://stackoverflow.com/questions/3923511/jquery-follow-scroll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!