向下滚动页面时,进度条会被填满。但我想要的是,当它们在屏幕上可见时,它们应该开始填充。如何实现?
$(window).scroll(function () {
var s = $(window).scrollTop(),
d = $(document).height(),
c = $(window).height();
scrollPercent = (s / (d-c)) * 100;
var position = scrollPercent;
$("#progressbar").attr('value', position);
$("#progressbar2").attr('value', position);
});
最佳答案
假设 1:您希望它们始终在屏幕上可见。一点 CSS 调整就可以了:
progress {
top:10px;
position:fixed;
right:10px;
}
#progressbar2 {
top: 40px;
}
演示:http://jsfiddle.net/ddh3t/1/
假设 2:当进度条可见时,您需要动画填充。这需要在 JS 中进行更改:
(来自 here 的 isScrolledIntoView)。
function isScrolledIntoView(elem) {
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
$(window).scroll(function () {
var s = $(window).scrollTop(),
d = $(document).height(),
c = $(window).height();
scrollPercent = (s / (d - c)) * 100;
var position = scrollPercent;
var p1 = $("#progressbar"), p2 = $("#progressbar2");
if(isScrolledIntoView(p1)) {
var val = 0, delay = 32, timer;
timer = setInterval(function() {
p1.attr('value', val++);
if(val>=position) clearInterval(timer);
},delay);
}
});
演示:http://jsfiddle.net/ddh3t/3/
注意p2(第二个进度条)可以用类似的方式填充。
最终更新:http://jsfiddle.net/ddh3t/6/
关于javascript - 当在屏幕上可见时,进度条应该开始填满,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22470919/