我正在用JavaScript编写一些计数器,我遇到了一个需要分隔符的大数问题。所以我为需要分隔符的计数器重写了一部分JavaScript。我创建了一个单独的函数来创建分隔符。我还构建了计数器应该从滚动上的页面偏移开始。这是我完整的JavaScript代码:
<script type="text/javascript">
jQuery(document).ready(function ($) {
var element_position = $("#projecten-in-beeld").offset().top;
$(window).on("scroll", function () {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = element_position;
if (y_scroll_pos > scroll_pos_test) {
$(".fact-inhoud").each(function () {
var $this = $(this),
countTo = $this.attr("data-count");
$({ countNum: $this.text() }).animate(
{
countNum: countTo,
},
{
duration: 3000,
easing: "linear",
step: function () {
$this.text(Math.floor(this.countNum));
},
complete: function () {
$this.text(this.countNum);
//alert('finished');
},
}
);
}); // end data-count
$(".fact-inhoud2").each(function () {
var $this = $(this),
countTo = $this.attr("data-count2");
$({ countNum: $this.text() }).animate(
{
countNum: countTo,
},
{
duration: 5000,
easing: "linear",
step: function () {
$this.text(commaSeparateNumber(Math.floor(this.countNum)));
},
complete: function () {
$this.text(commaSeparateNumber(this.countNum));
//alert('finished');
},
}
);
}); // end data-count
}
});
});
function commaSeparateNumber(val) {
while (/(d+)(d{3})/.test(val.toString())) {
val = val.toString().replace(/(d+)(d{3})/, "$1" + "." + "$2");
}
return val;
}
</script>
它工作得很好,当我在计数器所在的DIV处时,计数器开始运行。当我在计数器上滚动时,它们会停止并在停止的地方连续计数。当我滚动时,只有使用'commaSeparateNumber'函数作为分隔符的新计数器从零开始。
我怎么能因为某种原因杀死这个函数,只执行一次,而不是每次我再次滚动?
您可以使用布尔标志实现类似的结果:
<script type="text/javascript">
jQuery(document).ready(function ($) {
var isExecuted = false;
var element_position = $("#projecten-in-beeld").offset().top;
$(window).on("scroll", function () {
if (!isExecuted) {
// Your code
isExecuted = true;
}
}
}
</script>