Performing action repetitively on a click

孤街浪徒 提交于 2019-12-11 18:30:33

问题


i am not sure how to put this in words,so kindly bear with me .

I have a virtual keypad. In it there is a "backspace" button(div) that deletes a character on each click . i want it to be more realistic . so the question is "How do i delete multiple characters if the user is pressing the mouse down (i.e the mouse is pressed continously and the user hasn't lift his finger off the mouse )"

<div class="dialpadnumbers">1</div>
<div class="dialpadnumbers">2</div>
<div class="dialpadnumbers">3</div>
<div class="dialpadnumbers">4</div>
<div class="dialpadnumbers">5</div>
<div class="dialpadnumbers">6</div>
<div class="dialpadnumbers">7</div>
<div class="dialpadnumbers">8</div>
<div class="dialpadnumbers">9</div>
<div class="dialpadnumbers">0</div>
<div id="dialpadbackspace" class="dialpadnumbers">Backspace</div>
<div id="dialpadcall" class="dialpadnumbers">CALL</div>

/*also the jquery for it(the one ive been using till now is),caret is the fn          
for setting caret position*/
$("#dialpadbackspace").click(function() {
    $('#dialpadentry').focus();
    var init = $("#dialpadentry").val();
    var start = $("#dialpadentry")[0].selectionStart;
    var stop = $("#dialpadentry")[0].selectionEnd;
    if (start == stop) {
        var substr = init.substring(0, start);
        var newsubstr = init.substring(0, start - 1);
        var finale = init.replace(substr, newsubstr);
        $("#dialpadentry").val(finale);
        $('#dialpadentry').caret(start - 1);
    } else {
        var substr = init.substring(start, stop);
        var finale = init.replace(substr, '');
        $("#dialpadentry").val(finale);
        $('#dialpadentry').caret(start);
    }

回答1:


Basically on mousedown start a interval which calls a function every x milliseconds that removes a character from the dial. You already got two excellent answers, so I will just post a quick jsfiddle I did.

http://jsfiddle.net/EB29c/




回答2:


Check out setInterval. Bind the mousedown event to setInterval, store the ID somewhere, and the mouseup event to clearInterval.

Be sure to cover edge cases. For example, if the user clicks your backspace, then drags the mouse away without lifting the mouse button. onMouseOut will need to be bound to clearInterval. There may be other edge cases as well.




回答3:


try this

$(function () {
    var doBackspace;
    $("#dialpadbackspace").mousedown(function(e) {
        doBackspace = setInterval('$("#dialpadentry").val($("#dialpadentry").val().substr(0, $("#dialpadentry").val().length-1));',100);
    });
    $("#dialpadbackspace").mouseup(function(e) {
        clearInterval(doBackspace);
    });
})();


来源:https://stackoverflow.com/questions/11671863/performing-action-repetitively-on-a-click

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!