问题描述
我正在制作一个包含范围输入滑块的站点.我希望滑块可以根据滑块的值更改颜色.
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.
例如,如果值为0,则拇指颜色将为 rgb(255,0,0);
,如果值为100,则颜色将为 rgb(0,255,0);
,然后拇指会更改颜色.
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>
请记住,我对Java的了解很少,但是我知道许多其他编程语言,并且我足够了解大多数Javascript代码.因此,请尝试使其尽可能简单.
Please bear in mind that I know very little Javascript, however I know many other programming languages and I know enough to understand most Javascript code. So please try to make it as simple as is possible.
我将如何有效地做到这一点?
How would I be able to do this effectively?
推荐答案
这就是我要这样做的方式:我将创建一个新的< style>
元素,并将该元素附加到头.接下来,在输入时,我将编写一个css规则,使用hsl颜色将拇指的颜色从红色更改为绿色.我将使这个CSS规则成为新样式元素的文本内容.希望对您有帮助.
This is how I would do it: I would create a new <style>
element and I woild append this element to the head. Next on input I would write a css rule that would change the thumb's color from red to green using hsl colors. I would make this css rule the text content of the new style element. I hope it helps.
let s = document.createElement("style");
document.head.appendChild(s);
itr.addEventListener("input", () => {
s.textContent = `.slider::-webkit-slider-thumb{background-color: hsl(${itr.value}, 100%, 50%)}`
})
.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: hsl(50, 100%, 50%);
overflow: visible;
cursor: pointer;
}
.slidecontainer {
transform: translateY(-10px);
}
<div class="slidecontainer" align="center">
<input id="itr" type="range" min="0" max="100" value="50" class="slider" name="rangeInput">
</div>
这篇关于如何根据值更改输入滑块的拇指颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!