【发布时间】:2016-07-27 02:43:27
【问题描述】:
我有一个计数器,它动画到 HTML 中定义的最终数字。但是,我希望这个动画一旦出现在视口中。
我有一个fiddle here,它显示了滚动似乎如何影响计数器编号。
$(document).ready(function() {
$(function($, win) {
$.fn.inViewport = function(cb) {
return this.each(function(i, el) {
function visPx() {
var H = $(this).height(),
r = el.getBoundingClientRect(),
t = r.top,
b = r.bottom;
return cb.call(el, Math.max(0, t > 0 ? H - t : (b < H ? b : H)));
}
visPx();
$(win).on("resize scroll", visPx);
});
};
}(jQuery, window));
$(".fig-number").inViewport(function(px) {
$(this).each(function() {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 1000,
step: function(now) {
$(this).text(Math.ceil(now));
}
});
});
});
});
我尝试了多种方法,但似乎无法实现我所追求的目标。
$(document).ready(function() {
$(function($, win) {
$.fn.inViewport = function(cb) {
return this.each(function(i, el) {
function visPx() {
var H = $(this).height(),
r = el.getBoundingClientRect(),
t = r.top,
b = r.bottom;
return cb.call(el, Math.max(0, t > 0 ? H - t : (b < H ? b : H)));
}
visPx();
$(win).on("resize scroll", visPx);
});
};
}(jQuery, window));
$(".fig-number").inViewport(function(px) {
$(this).each(function() {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 1000,
step: function(now) {
$(this).text(Math.ceil(now));
}
});
});
});
});
html,
body {
height: 100%;
}
#upper-push {
height: 100%;
width: 100%;
display: block;
background: red;
color: white;
}
<div id="upper-push">
Scroll down
</div>
<div id="numbers">
<span class="fig-number">25</span>
<span class="fig-number">78</span>
</div>
【问题讨论】:
-
那么,一旦您向下滚动并且在视口内可见计数器文本,您希望滚动应该开始什么,然后如果再次向上滚动不应该受到影响/?
标签: jquery html counter viewport