当我到达一个特定的div时,我想让一个计数脚本被触发,但是当它到达div的顶部时,它会在到达底部时启动,为什么会这样?
我的HTML:
<div id="status_counter" class="status_bar">
<div class="container text-center">
<div class="row">
<div class="col-sm-3">
<div class="counter-item">
<h2><div class="counter" data-count="33">0</div></h2>
</div>
</div>
<div class="col-sm-3">
<div class="counter-item">
<h2><div class="counter" data-count="25">0</div></h2>!-
</div>
</div>
<div class="col-sm-3">
<div class="counter-item">
<h2><div class="counter" data-count="15">0</div></h2>
</div>
</div>
<div class="col-sm-3">
<div class="counter-item">
<h2><div class="counter" data-count="42">0</div></h2>
</div>
</div>
</div>
</div>
</div>
我的counter.js:
var eventFired = false,
objectPositionTop = $('#status_counter').offset().top;
$(window).on('scroll', function() {
var currentPosition = $(document).scrollTop();
if (currentPosition > objectPositionTop && eventFired === false) {
eventFired = true;
$('.counter').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({ countNum: $this.text()}).animate({
countNum: countTo
},
{
duration: 2000,
easing:'linear',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
//alert('finished');
}
});
});
}
});
目前:当向下滚动到status_counter时,它不会触发我的脚本,直到我向下滚动到它的底部。
我想在我的屏幕上出现status_counter div后立即触发我的Count up脚本,所以当status_counter div的top / start到达屏幕底部时。
答案 0 :(得分:0)
您需要检查元素的底部位置与窗口的底部位置(即scrollHeight +窗口高度):
objectPositionTop = $('#status_counter').offset().top;
objectPositionBottom = objectPositionTop + $('#status_counter').height();
在scroll
内你可以使用:
var currentPositionBottom = $(document).scrollTop() + $(window).height();
if (currentPositionBottom > objectPositionBottom && eventFired === false) {
这是你代码的一个分支:
https://jsfiddle.net/rop0g9gz/1/
答案 1 :(得分:0)
如果我理解你的问题,这应该有效:
var eventFired = false,
objectPositionTop = $('#status_counter').offset().top,
objectPositionBottom = objectPositionTop;
$(window).on('scroll', function() {
var currentPositionBottom = $(document).scrollTop() + $(window).height();
if (currentPositionBottom > objectPositionBottom && eventFired === false) {
eventFired = true;
$('.counter').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({countNum: $this.text()}).animate({
countNum: countTo
}, {
duration: 2000,
easing:'linear',
step: function() {
$this.text(Math.floor(this.countNum));
}, complete: function() {
$this.text(this.countNum);
}
});
});
}
});
答案 2 :(得分:0)
抓住你想要计算的div
:
var exampleDiv = document.getElementById("#YOUR-DIV-ID")
并将其附加到mouseover
事件:
exampleDiv.addEventListener('mouseover' , your-count-function)