Div在页面上按比例关注滚动条

Ser*_*lov 2 javascript css jquery scrollbar sticky

我现在正在苦苦寻找一个应该在页面上按比例滚动的粘性元素.尽管页面的高度,从顶部到页脚.所以它实际上在开始时粘在滚动条的顶部,然后在结尾处粘到底部.或者只是跟随滚轮.

有没有机会用jQuery做到这一点?

下面是通常的"粘性"div的起始代码.

$(window).scroll(function(){
$("#sticky")
.animate({"marginTop":($(window).scrollTop())+"px"}, "fast");});
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/flakessp/cxr78xc8/

Mar*_*cel 5

你的意思是这样的吗?

$(window).scroll(function() {

    // calculate the percentage the user has scrolled down the page
    var scrollPercent = 100 * $(window).scrollTop() / ($(document).height() - $(window).height());

    // get the height of the sticky element
    var stickyHeight = $('.sticky').height();

    // calculate the margin top of the sticky element
    var marginTop = (($(window).height() - stickyHeight) / 100) * scrollPercent;

    // set margin top of sticky element
    $('.sticky').css('marginTop', marginTop);
});
Run Code Online (Sandbox Code Playgroud)

小提琴