【发布时间】:2019-10-10 10:03:28
【问题描述】:
我有一些进度条,我需要它们在滚动时开始加载。但是,jQuery 函数仅在页面仅加载到该部分时才起作用,并且当我稍微滚动页面时(当它仍在视口中时)该函数停止工作。如果页面从顶部加载并且我向下滚动到此部分,则它根本不起作用。
我尝试了不同的方法让它在视口中工作,所有这些都导致了同样的问题。 我也试过 $(window).on("resize scroll", function ()).
关于如何修复它的任何想法?
$.fn.isInViewport = function() {
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
$(window).on("scroll", function() {
$(".radialbar").each(function() {
var $bar = $(this).find(".radialbar--bar");
var $val = $(this).find(".radialbar__value-int");
var perc = parseInt($val.text(), 10);
if ($(this).isInViewport()) {
$({
p: 0
}).animate({
p: perc
}, {
duration: 3000,
easing: "swing",
step: function(p) {
$bar.css({
transform: "rotate(" + (45 + (p * 1.8)) + "deg)", // 100%=180° so: ° = % * 1.8
// 45 is to add the needed rotation to have the green borders at the bottom
});
$val.text(p | 0);
}
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="radialbar">
<div class="radialbar--base">
<div class="radialbar--bar"></div>
</div>
<div class="radialbar__value">
<span class="radialbar__value-int">100</span>
<span class="radialbar__value-perc">%</span>
</div>
<div class="radialbar__title">
Title
</div>
</div>
【问题讨论】:
标签: javascript jquery function scroll