JQuery:在间隔中减少mousedown选定输入的值,在mouseup

时间:2015-08-19 19:46:39

标签: javascript jquery html

我在这里有一个有趣的。

我所拥有的是一些包含隐藏输入值的DIV。我希望用户能够" mousedown"在其中一个DIV和JQuery上会获得" id"该特定DIV中的输入。 (将是block-1,block-2,block-3等)。

以下是那些DIV

<div class="block" id="1"><input id="block-1" value="3" type="hidden"></div>
<div class="block" id="2"><input id="block-2" value="3" type="hidden"></div>
<div class="block" id="3"><input id="block-3" value="3" type="hidden"></div>

现在JQuery已经获得了正确的输入ID,只要mousedown仍处于活动状态,我就希望每200毫秒左右将值减少1。但是如果用户释放(mouseup),那么该值将重置为原始值(在本例中为3)。

如果您想知道我为什么要这样做,我原来的计划是让选定的DIV在值减小时更改颜色或内容。但是,如果该值最终达到0,那么DIV将被隐藏。

我试图work from this,但我一直感到难过。

1 个答案:

答案 0 :(得分:0)

您可以使用setInterval代替setTimeout

<强> JS

$("input").mousedown(function(e) {
    var self = $(this);
    clearInterval(this.downTimer);
    this.downTimer = setInterval(function() {
      self.val(self.val() - 1);
    }, 200);
}).mouseup(function(e) {
    clearInterval(this.downTimer);
    var val = $(this).prop("defaultValue");
    $(this).val(val);
});

Fiddle

注意:在示例中,我使用了type=text而不是type=hidden,因此可以进行测试。