长按按钮,多次触发功能

时间:2014-04-26 20:33:10

标签: javascript jquery html

假设有 -

<script>
    function move() {...}
</script>
<input type="button" value="move">

FIDDLE

如果长按move(),我怎么能触发<input type="button" value="move">

例如 -

按1秒钟会调用move() 50次,按2秒会调用100次,依此类推。

可以找到一个用于长时间测量印刷的脚本here

使用jQuery的解决方案也是可以接受的。

3 个答案:

答案 0 :(得分:1)

试试这段代码:)

$(document).ready(function () {

    var longpress = false;
    var interv;

    function move()
    {
        console.log("move");    
    }

    $("button").on('click', function () {
        (longpress) ? alert("Long Press") : alert("Short Press");
    });

    var startTime, endTime;
    $("button").on('mousedown', function () {
        startTime = new Date().getTime();
        interv = setInterval(function(){
            move();
        }, 100);
    });

    $("button").on('mouseup', function () {
        endTime = new Date().getTime();
        longpress = (endTime - startTime < 500) ? false : true;
        clearInterval(interv);
    });

});

DEMO:http://jsfiddle.net/pZ6FR/1/

答案 1 :(得分:0)

检查此解决方案:

function holdit(btn, action, start, speedup) {
    var t;

    var repeat = function () {
        action();
        t = setTimeout(repeat, start);
        start = start / speedup;
    }

    btn.mousedown = function() {
        repeat();
    }

    btn.mouseup = function () {
        clearTimeout(t);
    }
};

/* to use */
holdit(btn, function () { }, 1000, 2); /* x..1000ms..x..500ms..x..250ms..x */

取自this Stackoverflow问题

答案 2 :(得分:0)

我会将move()函数传递给包含您要执行的迭代次数的变量。然后,让move()函数递归调用,直到var iterations为0。

我会看到它看起来像这样:

<script>
function move(iterations){
  //do actions
  //...
  //check if move() should run again
  if(iterations > 0){
    move(iterations-1);
  }
}

现在,你的pressTime()函数只需要调用带有所需迭代的move()。希望这会有所帮助。

相关问题