色相/饱和度/最轻范围滑块的功能

时间:2019-04-09 23:53:18

标签: javascript html

enter image description here enter image description here否->

   <div id="colorSpec">
                HEX color: 
                 <!-- The user insert the color the div will have-->
                <input id="userColor" type="text"> <br>
                <input id="doitButton" type="button" value="Do it !"> <br>

                 <!-- Range slider to set the opacity-->
                <input id="mySlider"  type= "range" step=".01" min="0" max="1" value=".5">
            </div>

   doitButton.addEventListener("click", function(ev){
                //alert("got a click!");
                var textelement= document.getElementById('userColor');
                var hcolor= textelement.value;
                console.log("hcolor is " + hcolor);
                //set the color took from the input "userColor
                colorBox.style.backgroundColor= hcolor;
                });
                mySlider.addEventListener("input",function(ev){
                 //set the opacity
                colorBox.style.opacity=mySlider.value;
                
                })
    }

我正在使用范围输入来修改div的背景颜色。我正在使用javascript函数来执行此操作,并且已经使用div的不透明度进行了此操作,但是当我尝试使用饱和度,色相和最亮(hsl)时,它没有相同的输出。我想知道为什么不起作用是因为我不能为代码使用相同的结构。 我将向您展示我对不透明度范围输入所做的操作:

[enter image description here 结果:

1 个答案:

答案 0 :(得分:1)

只需将HSL值设置为字符串即可。除此之外,应该注意,在DOM中,似乎总是将其转换回rgb()rgba()。即使按照spec手动设置样式属性字符串也是如此。

  

如果该值是半透明的,则计算出的值为rgba()对应的值。如果不是,它将是rgb()对应的那个。透明关键字映射到rgba(0,0,0,0)

update = () => {
  let hsl = `hsl(${mySlider1.value||0}, ${mySlider2.value||0}%,${mySlider3.value||0}%)`;
  colorBox.style.backgroundColor = hsl;
};

mySlider1.addEventListener("input", update);
mySlider2.addEventListener("input", update);
mySlider3.addEventListener("input", update);
update();
#colorBox {
  width: 100px;
  height: 100px;
}
<div id="colorSpec">
  <!-- Range slider to set the opacity-->
  <input id="mySlider1" type="range" step="1" min="0" max="260" value="180">
  <input id="mySlider2" type="range" step="1" min="0" max="100" value="50">
  <input id="mySlider3" type="range" step="1" min="0" max="100" value="50">
</div>
<div id="colorBox"></div>