如果按住鼠标,可以指定一个清除输入字段的功能吗?目前我已经获得了以下http://jsfiddle.net/e1kb6esm/6/,如果你点击一个字段,它会增加一个,但我还需要做的是能够清除该字段,如果它被错误点击了。我在考虑与
有关if $this.mousedown(function(e) {
但是,如果我清除了mousedown,那么它也会清除点击次数增加的值吗?
代码:
<input class="played" type="text" value="" /><br>
<input class="played" type="text" value="" /><br>
<input class="played" type="text" value="" /><br>
<input class="played" type="text" value="" /><br>
<input class="played" type="text" value="" />
$('.played').on('focus', function () {
var $this = $(this);
if ($this.val() == '') {
$this.val('1');
$this.blur();
} else {
var value = parseInt($this.val());
$this.val(value + 1);
$this.val();
$this.blur();
}
});
答案 0 :(得分:3)
要实现此目的,您可以在mousedown
事件触发时启动计时器。然后,当5秒倒计时完成时,此事件将清除该字段。如果提前释放鼠标,您还需要挂钩mouseup
事件以清除计时器。试试这个:
var timer;
$('.played').on({
'focus': function () {
$(this).val(function (i, v) {
return (+v || 0) + 1;
}).blur();
},
'mousedown': function () {
var $el = $(this);
timer = setTimeout(function () {
$el.val('');
}, 5000);
},
'mouseup': function () {
clearTimeout(timer);
}
});
请注意,我还略微改进了递增逻辑。
答案 1 :(得分:0)
您可以设置超时功能,在5秒后执行,检查鼠标按钮是否仍然按下。
setTimeout(checkIfClickedFive, 5000);
function checkIfClickedFive() {
if(clicked){
element.val('');
}
};
在mouseup上你清除了这个超时功能,这样如果你不想要它们就不会被执行。
$('.played').off('focus', function () {
clicked = false;
clearTimeout();
});
查看修改后的Fiddle。
点击的变量是全局变量。它基本上是多余的,但我总是对超时有点过分谨慎,特别是clearTimeout方法......
答案 2 :(得分:0)
这适合您的需要吗? http://jsfiddle.net/3oqa3796/
我添加了此代码(来自how to calculate time during mousedown event in jquery?):
$('.played').mousedown(function(e) {
console.log($(this));
var element = $(this);
clearTimeout(this.downTimer);
this.downTimer = setTimeout(function() {
element[0].value="";
console.log(element);
}, 5000);
}).mouseup(function(e) {
clearTimeout(this.downTimer);
});