繁体   English   中英

实施并按住按钮

[英]Implement press and hold on a button

感谢您之前(由主持人删除)的解释和简单的实现,但对我而言不起作用。 'holdit'函数可以工作,但是它不是很稳定,可能是因为'holdit'函数中也有一个'onmouseup'。即使我在HTML按钮上禁用了onmouseup,它也不是很稳定。 也许最好使用addEventListener- onmousedown-interval函数,但是我也不知道如何以最简单的方式实现它。 这是完整的功能,它显示一个按下的按钮,并将timeSeconds var加1。 为了安全起见, 数量在限制范围内。 请帮忙。

     HTML:
    <img id="but4" class="button" src= "//:0" onmousedown="timesecPlus();"onmouseup="timesecPlsUp();"/>

     JAVASCRIPT:
    function timesecPlus() {
    var pmknop = document.getElementById('but5');
    pmknop.src = secminBtndwn; //inline Base64 data: button image down (pressed) 

    timeSeconds = ((timeSeconds>wedstrijdperiode.seconden-6)?(timeSeconds):(++timeSeconds)); //You can ++ chase-back the timeseconds until 5 sec's from   period start-time
    displayTime( timeSeconds ); 
    };

    function timesecPlsUp() {
    var pmknop = document.getElementById('but5'); 
    pmknop.src = secminBtn; //inline Base64 data: button image up (normal)
    };

   // Things I tried:
   //holdit(pmknop, function () { ++timeSeconds ; displayTime( timeSeconds );}, 2000, 2);
   //pmknop = pmknop.addEventListener('mousedown', function() { interval = setInterval(timesecPlus (), 2000); });


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

    var repeat = function () {
    action();
    t = setTimeout(repeat, start);
    start = start / speedup;
    }
    btn.onmousedown = function() {
    repeat();
    }
    btn.onmouseup = function () {
    clearTimeout(t);
    }
     }; 

简单实施:

var btn = document.getElementsByClassName('button')[0];
holdit(btn, function () { timeSeconds++ ; displayTime( timeSeconds );}, 1000, 2);

没有holdit的实现:

var btn = document.getElementsByClassName('button')[0];
var couterFunc, couter=0;
btn.addEventListener('mousedown',function(){couterFunc = setInterval(update,1000); update()})
btn.addEventListener('mouseup',function(){clearInterval(couterFunc)})

/* function that will fire when button press*/
function update(){console.log(++couter)};

holdit函数采用四个变量。 第一个:btn,是按钮的ID。 这用于确定每当单击鼠标时执行的操作。

第二个变量是对函数的引用。 它称为回调函数,因为您将在每次调用holdit时传递一个将被Caaalleed的函数。

最后两个变量仅确定延迟重复执行的时间和时间,以及每次重复执行将加速多少时间。

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

Repeat是一个递归函数,将在“开始”毫秒后调用,并在每次迭代后更频繁地重复。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM