Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 0, the thumb colour would be rgb(255, 0, 0);, if it were 100, the colour would be rgb(0, 255, 0);, and the thumb would change colour.

To be clear, I don't want something like this:

if slider_value <= 29:
  thumb_color = rgb(255, 0, 0)
else if slider_value >= 30 && slider_value <= 69:
  thumb_color = rgb(255, 255, 0)
else 
  thumb_color = rgb(0, 255, 0)

Here's the code I have so far:

.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 {
  -webkit-appearance: none;
  width: 18px;
  height: 18px;
  border-radius: 10px;
  background-color: rgb(255, 120, 0);
  overflow: visible;
  cursor: pointer;
}

.slidecontainer {
  transform: translateY(-10px);
}
<div class="slidecontainer" align="center">
  <input type="range" min="0" max="100" value="50" class="slider" name="rangeInput">
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
701 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 */
<div class="slidecontainer">
  <input type="range" min="0" max="100" value="50" class="slider" name="rangeInput">
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...