我的页面上有两个数字代码,两个代码都合并为一个。
演示:
$(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%'
});
})
// 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: 20px;
}
.gap2 {
margin: 20px 0px;
background: red;
height: 50px;
}<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 id="ticker">
<span class="count counter">16,000+</span>
</div>
<div class="gap"></div>
<div id="ticker">
<span class="count counter">$64 million</span>
</div>
<div class="gap2">Expected output below (but they obviously count up to that number)</div>
<!-- expected output -->
<div id="ticker">
<span>16,000+</span>
</div>
<div class="gap"></div>
<div id="ticker">
<span>$64 million</span>
</div>
为什么会发生这种情况?我相信问题就在这条线上:
const format = formatter(initialValue)因为当注释掉时,虽然它不计数,但它只显示一个数字。但不明白为什么会导致这种合并?
编辑:
已经编辑了片段,以展示预期的最终结果。
发布于 2019-10-11 15:48:31
是的,你是对的。请更换
const format = formatter(initialValue)使用
const format = formatter($(this).text());这个变化会给你带来预期的产出。
您正在遍历每个“计数”div,因此不需要将其存储在变量中,因为".text()“行包含所有”计数“div的输出。
因此,在循环中获取div的文本。
https://stackoverflow.com/questions/58344119
复制相似问题