我找到了一个不错的 jquery 增量脚本。增量部分可以接受一个函数或只是一个常规数字。我希望以 1 到 100 之间的随机数增加。我将如何为此编写函数?
$( document ).ready( function()
{
$( '.tick' ).ticker(
{
incremental : 1,
delay : 1500,
separators : true
});
$(".comma-change").html(".");
});
<span class="tick">2,354,456</span>
因此,我不想在增量字段中增加 1,而是编写一个用随机数更新的函数。在其他帖子的帮助下,我可以毫无问题地编写创建随机数的函数:
function random_generator (min, max) {
return Math.random() * (max - min) + min;
}
但我无法直接将其用于此。
这是插件的增量部分:
Tick = (function() {
function Tick(element, options) {
this.element = element;
if (options == null) options = {};
this.running = false;
this.options = {
delay: options.delay || 1000,
separators: options.separators != null ? options.separators : false,
autostart: options.autostart != null ? options.autostart : true
};
this.increment = this.build_increment_callback(options.incremental);
this.value = Number(this.element.html().replace(/[^\d.]/g, ''));
this.separators = this.element.html().trim().split(/[\d]/i);
this.element.addClass('tick-active');
if (this.options.autostart) this.start();
}
Tick.prototype.build_increment_callback = function(option) {
if ((option != null) && {}.toString.call(option) === '[object Function]') {
return option;
} else if (typeof option === 'number') {
return function(val) {
return val + option;
};
} else {
return function(val) {
return val + 1;
};
}
};
然后这一点:
Tick.prototype.tick = function() {
this.value = this.increment(this.value);
this.render();
return this.set_timer();
};
最佳答案
您可能需要更新增量脚本的源代码。但是,如果幸运的话,您也许可以使用一些技巧来避免这种情况。
增量脚本中可能有这样的东西:
function(options) {
//...
currentValue += options.incremental;
//...
}
如果是这种情况,您可以在事后定期调整 options.incremental
的值,如下所示:
var opts;
$( '.tick' ).ticker(opts = {
incremental : 1,
delay : 1500,
separators : true
});
setInterval(function () {
var min = 1, max = 100; //adjust min/max to suit your needs.
opts.incremental = Math.random() * (max - min) + min;
}, 500); //any number under 1500 is probably fine
这有点 hack,但它可能会起作用。可能比更新插件代码更容易。如果它不起作用,您可能必须直接增强插件。
关于javascript - 如何为这个 jquery 增量插件编写一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12482202/