How to change the input slider thumb colour depending on value?

前端 未结 4 1488
小蘑菇
小蘑菇 2021-01-24 11:03

I\'m making a site that includes a range input slider. I would like the slider thumb to change colour according to the value of the slider.

For example, if the value was

4条回答
  •  攒了一身酷
    2021-01-24 12:05

    You're basically looking for this, right?

    const input = document.querySelector('input[type="range"]');
    const style = document.createElement('style');
    const head = document.head || document.getElementsByTagName('head')[0];
    style.type = 'text/css';
    head.appendChild(style);
    input.oninput = function(e) {
      const cssText = `input.slider::-webkit-slider-thumb, input.slider::-moz-range-thumb {
        background-color: rgb(${255 - 2.55*e.target.value}, ${2.55*e.target.value}, 0);
      }`;
      if (style.styleSheet) {
        style.styleSheet.cssText = cssText;
      } else {
        style.innerHTML = "";
        style.appendChild(document.createTextNode(cssText));
      }
    }
    .slider {
      width: 60%;
      margin: 50px auto;
      -webkit-appearance: none;
      height: 8px;
      border-radius: 4px;
      margin-bottom: 15px;
      background-color: rgb(200, 200, 200);
    }
    
    .slider::-webkit-slider-thumb, 
    .slider::-moz-range-thumb {
      -webkit-appearance: none;
      width: 18px;
      height: 18px;
      border-radius: 10px;
      background-color: rgb(128, 128, 0);
      overflow: visible;
      cursor: pointer;
    }
    
    .slidecontainer {
      transform: translateY(-10px);
    }
      

    It's a bit trickier as ::webkit-slider-thumb is a pseudo element and (i might be wrong here) i don't think you can target it directly with JavaScript. So what I did was add a