【问题标题】:Div to follow scrollbar proportionally on a pageDiv 在页面上按比例跟随滚动条
【发布时间】:2015-05-13 07:58:16
【问题描述】:
我现在正在努力研究一个应该在页面上按比例滚动的粘性元素。尽管页面的高度从顶部到页脚。所以它实际上是在开始时粘在滚动条的顶部,然后在结束时粘在底部。或者它只是跟随滚轮。
有没有机会用 jQuery 做到这一点?
下面是带有通常“粘性” div 的起始代码。
$(window).scroll(function(){
$("#sticky")
.animate({"marginTop":($(window).scrollTop())+"px"}, "fast");});
https://jsfiddle.net/flakessp/cxr78xc8/
【问题讨论】:
标签:
javascript
jquery
css
scrollbar
sticky
【解决方案1】:
你的意思是这样的吗?
$(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);
});
Fiddle
【解决方案2】:
所以,这个有点棘手,但它是:
基本上,我们在这里使用了一些东西:
使用此部分进行滚动方向检测:
var lastScrollPos = 0,
...
lastScrollPos < $window.scrollTop()
然后,您忘记了考虑文档和窗口高度等因素。 scrollTop 完全按照它所说的做,只给你从视口顶部到文档顶部的数字。所以我们用$(window).height()添加可见高度。
那么这只是我们是否也考虑元素高度的问题(因此三元运算符添加0 或$('#sticky').height() 取决于我们在前面部分的滚动方向检测。
总之,这是完整的 JS:
var lastScrollPos = 0,
$window = $(window),
$document = $(document),
$sticky = $('#sticky');
$(window).scroll(function(){
$sticky
.animate({"top":((($window.scrollTop() + (lastScrollPos < $window.scrollTop() ? $window.height() - $sticky.height() : 0))/$document.height()) * 100)+"%"}, "fast");
});