我有一个数字计数器,并且在查看#ticker
div时使用航点来运行计数器。
当看到div时,计数器开始计数,所以这不是问题。但是这是我当前问题的用例:
16,000+
的静态值时。15,604+
,此时它应始终以16,000+
结尾]。不确定为什么会这样吗?
demo:
$(document).ready(function() {
$('#ticker').waypoint({
handler: function() {
$('.count').each(function() {
const initial = $(this).text()
const format = formatter(initial)
$(this).prop('Counter', 0).animate({
Counter: format.value
}, {
duration: 1500,
easing: 'swing',
step: function(now) {
$(this).text(format.revert(Math.ceil(now)));
}
});
});
},
offset: '100%'
});
})
// keep string after count
function formatter(str) {
const char = 'x'
const template = str.replace(/\d/g, char)
const value = str.replace(/\D/g, '')
function revert(val) {
const valStr = val.toString()
let result = ''
let index = 0
for (let i = 0; i < template.length; i++) {
const holder = template[i]
if (holder === char) {
result += valStr.slice(index, index + 1)
index++
} else {
result += holder
}
}
return result
}
return {
template: template,
value: value,
revert: revert
}
}
.gap{
background: lightgrey;
height: 600px;
}
.gap2{
background: blue;
height: 600px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/jquery.waypoints.min.js"></script>
<div class="gap"></div>
<div id="ticker">
<span class="count counter">16,000+</span>
</div>
<div class="gap2"></div>
如果向下滚动直到ticker
并等待16000完成,然后再次向上滚动并等待16000完成然后再次下降,它将起作用。
该代码绝对正确,除了此行const initial = $(this).text()
。您正在使用跨度元素文本本身来获取最大计数器数。
[每当滚动速度太快时,代码都会将span元素中存在的任何值设置为最大计数器。这就是为什么您出现有线行为的原因。
请像这样重写您的处理程序代码
$(document).ready(function () {
var initialValue = $('#ticker .count').text()
$('#ticker').waypoint({
handler: function () {
$('.count').each(function () {
const format = formatter(initialValue)
$(this).prop('Counter', 0).animate({
Counter: format.value
}, {
duration: 1500,
easing: 'swing',
step: function (now) {
$(this).text(format.revert(Math.ceil(now)));
}
});
});
},
offset: '100%'
});
})