我想知道当“about”div 处于 View 中时如何激活此 jQuery。 或者当我们滚动 div 时。
(function($) {
$.fn.countTo = function(options) {
options = options || {};
return $(this).each(function() {
var settings = $.extend({}, $.fn.countTo.defaults, {
from: $(this).data('from'),
to: $(this).data('to'),
speed: $(this).data('speed'),
refreshInterval: $(this).data('refresh-interval'),
decimals: $(this).data('decimals')
}, options);
var loops = Math.ceil(settings.speed / settings.refreshInterval),
increment = (settings.to - settings.from) / loops;
var self = this,
$self = $(this),
loopCount = 0,
value = settings.from,
data = $self.data('countTo') || {};
$self.data('countTo', data);
if (data.interval) {
clearInterval(data.interval);
}
data.interval = setInterval(updateTimer, settings.refreshInterval);
render(value);
function updateTimer() {
value += increment;
loopCount++;
render(value);
if (typeof(settings.onUpdate) == 'function') {
settings.onUpdate.call(self, value);
}
if (loopCount >= loops) {
// remove the interval
$self.removeData('countTo');
clearInterval(data.interval);
value = settings.to;
if (typeof(settings.onComplete) == 'function') {
settings.onComplete.call(self, value);
}
}
}
function render(value) {
var formattedValue = settings.formatter.call(self, value, settings);
$self.html(formattedValue);
}
});
};
$.fn.countTo.defaults = {
from: 0,
to: 0,
speed: 1000,
refreshInterval: 100,
decimals: 0,
formatter: formatter,
onUpdate: null,
onComplete: null
};
function formatter(value, settings) {
return value.toFixed(settings.decimals);
}
}(jQuery));
jQuery(function($) {
// custom formatting example
$('.count-number').data('countToOptions', {
formatter: function(value, options) {
return value.toFixed(options.decimals).replace(/\B(?=(?:\d{3})+(?!\d))/g, ',');
}
});
$('.timer').each(count);
function count(options) {
var $this = $(this);
options = $.extend({}, options || {}, $this.data('countToOptions') || {});
$this.countTo(options);
}
$(function() {
$('div[onload]').trigger('onload');
});
});
最佳答案
您可以将代码设置为非匿名函数,并使用 jQuery 的 Waypoints 插件来触发该函数。
如果您不想使用插件,则可以触发 $(window).scroll()
内的函数并进行一些计算。首先注释掉这一行:$('.timer').each(count);
。您可以将该行包裹在滚动检查器内,如下所示:
//listening scrolling action
$(window).scroll(function() {
var div_start = $("#about-row-b").offset().top;
var div_final = $("#about-row-b").offset().top + $("#about-row-b").outerHeight();
var viewport_end = $(window).scrollTop() + $(window).height();
if((viewport_end > div_start) && (viewport_end < div_final)){
// v v v call your function here!!!
$('.timer').each(count);
}
});
如果您只对上升的数字感兴趣,您可能需要检查 Benjamin Intal's Counter Up jQuery plugin .
关于jquery - 在div View 上执行JQuery函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42443045/