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

前端 未结 4 1461
小蘑菇
小蘑菇 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 11:45

    the simplest is to use a variable css. see : https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties

    const Slider = document.querySelector('input[name=rangeInput]')
    
    Slider.oninput =_=> Slider.style.setProperty('--SliderColor', `hsl(${Slider.value}, 100%, 50%)`)
    .slidecontainer {
      transform: translateY(-10px);
      text-align: center;
    }
    .slider {
      --SliderColor: hsl(50, 100%, 50%);
      -webkit-appearance: none;
      width: 60%;
      margin: 50px auto;
      height: 8px;
      border-radius: 4px;
      margin-bottom: 15px;
      background-color: rgb(200, 200, 200);
    }
    
    /* --------------------------- webkit browsers */
    .slider::-webkit-slider-thumb {
      -webkit-appearance: none;
      width: 18px;
      height: 18px;
      border-radius: 10px;
      background-color: var(--SliderColor);
      overflow: visible;
      cursor: pointer;
    }
    /* -------------------------- Firefox */
    .slider::-moz-range-thumb { 
      -moz-appearance: none;
      width: 18px;
      height: 18px;
      border-radius: 10px;
      background-color: var(--SliderColor);
      overflow: visible;
      cursor: pointer;
    }
    .slider::-moz-focus-outer { border: 0; }
    /* Remove dotted outline from range input element focused in Firefox */

    [edit]: adding css .slider::-moz-range-thumb (Firefox)

提交回复
热议问题