我有一个可以计数的数字自动收报机。出于演示目的,这就是计数器的工作方式。它计数然后停止。
现在,我试图让代码脚本#ticker
在视图中执行。为此,我使用waypoints
. 但是,我遇到以下问题:
- 脚本不会
#ticker
在视图中立即执行。事实上,我必须滚动过去,然后当我向上滚动时,它开始计数。 - 计数器在向上计数,到达结束数字,然后向下计数?我只希望它向上计数并停止在结束数字加上字符串(在本例中为 16,000+)。
为什么会这样?
演示:
$(document).ready(function() {
$('#ticker').waypoint(function() {
$('.count').each(function() {
const initial = $(this).text()
const format = formatter(initial)
$(this).prop('Counter', 0).animate({
Counter: format.value
}, {
duration: 3000,
easing: 'swing',
step: function(now) {
$(this).text(format.revert(Math.ceil(now)));
}
});
});
});
})
function formatter(str) {
// const delimeter = '-'
const char = 'x'
const template = str.replace(/\d/g, char)
const value = str.replace(/\D/g, '')
function revert(val) {
// need better solution
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;
}
<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="gap"></div>