延迟mousedown间隔启动(JQuery/Javascript) [英] Delay mousedown interval start (JQuery / Javascript)

查看:111
本文介绍了延迟mousedown间隔启动(JQuery/Javascript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个jQuery插件,该插件可在按下按钮时操纵输入字段的值.

I am writing a jQuery plugin that manipulates the value of an input field at the press of a button.

到目前为止,我拥有的功能是可以通过单击按钮来控制该值,并且如果用户按住该按钮,则可以不断增加该值. 简化后,脚本是这样的:

What I have so far is the ability to control the value by clicking the button, as well as to continually increase it if the user holds the button pressed. Simplified, the script is something like this:

var element = $('#test-input');
var interval;

$('#test-up-button').on({
    mousedown : function(e) {
        element.val(parseInt(element.val()) + 1);

        //Wait 400ms, than do the interval

        interval = window.setInterval(function() {
            element.val(parseInt(element.val()) + 1);
        }, 200);      
        e.preventDefault();        
    },
    mouseup : function() {
        window.clearInterval(interval);
    }
});

(您还可以在此处看到可用的版本: http://jsfiddle.net/Husar/Hxhsh /#base )

(You can also see a working version here: http://jsfiddle.net/Husar/Hxhsh/#base )

但是,正如您在注释中看到的那样,我还希望当mousedown事件发生时,在初始增加该值之后,将interval函数延迟400ms,然后才执行.

However, as you can see in the comment, I also want when the mousedown event happens, after the initial increase of the value, the interval function to be delayed for 400ms, and only than to execute.

按下按钮,数值变为+ 1,按住按钮不动,间隔开始滚动.

So that you press the button, value goes + 1, you hold the button a bit, and than the intervals start to roll.

推荐答案

setInterval包裹在setTimeout中.并且,像interval一样,保留并清除timeout值:

Wrap the setInterval in a setTimeout. And, like interval, keep and clear a timeout value:

var interval, timeout;

// ...

    timeout = window.setTimeout(function () {
        interval = window.setInterval(function() {
            element.val(parseInt(element.val()) + 1);
        }, 200);      
    }, 400);

// ...

    window.clearTimeout(timeout);
    window.clearInterval(interval);

http://jsfiddle.net/coiscir/jUSg8/

这篇关于延迟mousedown间隔启动(JQuery/Javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆