Incrementing value continuously on mouse hold

前端 未结 4 1768
终归单人心
终归单人心 2020-12-20 14:49

I have an HTML5 \'range\' control to which I want to add a plus (+) and minus (-) buttons on either sides.

The fiddle works fine, except that the value increase (or

4条回答
  •  再見小時候
    2020-12-20 15:52

    The very basic approach to this is to start looping at certain interval while one of buttons is pressed, doing value changes at each tick. Start when button is clicked, stop when it's released. Here's simplistic code for concept demonstration purpose only:

    // Store the reference
    var range = $('#range');
    
    // These functions will change the value
    function increment () {
        range.val(parseInt(range.val()) + 1)
    }
    
    function decrement () {
        range.val(parseInt(range.val()) - 1)
    }
    
    // Attaches polling function to element
    function poll (el, interval, fn) {
        var isHeldDown = false;
    
        return el
        .on("mousedown", function() {
            isHeldDown = true;
    
            (function loop (range) {
                if (!isHeldDown) return; // Stop if it was released
                fn();
                setTimeout(loop, interval); // Run the function again       
            })();
        })
        .on("mouseup mouseleave", function () {
            isHeldDown = false; // Stop polling on leave or key release
        });
    }
    
    poll($("#plus"), 40, increment);
    poll($("#minus"), 40, decrement);
    

    JSFiddle.

    In production grade version you'd want to apply timing function instead of constant interval; think about all possible events that should start and stop the polling so it won't stuck forever when user moves pointer away or something; use requestAnimationFrame to control timing function more precisely.

提交回复
热议问题