Prevent mousedown event on input range html element and still let user drag slider

后端 未结 5 1531
情书的邮戳
情书的邮戳 2021-02-20 02:15

So is there a way to disable mousedown and / or click event on input range element but at the same time let user drag slider around and still fire on change event?

Disabl

5条回答
  •  难免孤独
    2021-02-20 03:08

    Here's a pure CSS solution

    You can control parts of the range with CSS and in that way disable the pointer events for all of those parts them except the thumb of the slider. In this way, click events are only registered when the button of the slider is clicked.

    pointer-events: none;          // disable all event on the range
    

    Use the pseudo-class selectors to target the thumb and cover all major browsers like this.

    input[type=range]::-webkit-slider-thumb {   // support webkit (e.g. Chrome/Safari)
    input[type=range]::-moz-range-thumb {       // support for Firefox
    input[type=range]::-ms-thumb                // support for IE 
    

    Here's how that would look in action.

    $("#slider").on('mousedown', function(event) {
      console.log('Mouse-down: only fired when thumb of the range is clicked');
    });
    $("#slider").on('mouseup', function(event) {
      console.log('Mouse-up: only fired when thumb of the range is clicked');
    });
    input[type=range] {
      pointer-events: none;
    }
    
    input[type=range]::-webkit-slider-thumb {
      pointer-events: auto;
    }
    
    input[type=range]::-moz-range-thumb {
      pointer-events: auto;
    }
    
    input[type=range]::-ms-thumb {
      pointer-events: auto;
    }
    
    

    More information on pointer-events can be found in the MDN docs.

提交回复
热议问题