JavaScript使用Range调色及透明度实例
颜色搭配是件头疼的事,工作空隙,利用range做个简单的手动调色,可得到rgb值和相应的十六进制色值。因为用到range标签,建议使用搜狗、火狐,IE10及以上版本代码如下:
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="utf-8">
<!--AlwaysforcelatestIErenderingengine(eveninintranet)&ChromeFrame
Removethisifyouusethe.htaccess-->
<metahttp-equiv="X-UA-Compatible"content="IE=edge,chrome=1">
<title>test16_color</title>
<metaname="description"content="">
<metaname="author"content="Administrator">
<metaname="viewport"content="width=device-width;initial-scale=1.0">
<!--Replacefavicon.ico&apple-touch-icon.pngintherootofyourdomainanddeletethesereferences-->
<linkrel="shortcuticon"href="/favicon.ico">
<linkrel="apple-touch-icon"href="/apple-touch-icon.png">
<styletype="text/css">
body,div,span{margin:0;padding:0;}
.div1{margin:20pxauto;border:1pxsolidblack;width:400px;height:250px;opacity:1;}
.div2{margin:0auto;width:600px;text-align:center;}
span{width:180px;display:inline-block;text-align:right;}
span.val{width:50px;display:inline-block;text-align:left;}
input{margin:3px15px;outline:none;}
h2{margin:3pxauto;}
</style>
</head>
<body>
<divclass="div1"id="div1">
</div>
<divclass="div2">
<h2><span>R(红色):</span><spanclass="val"id="rValue">255</span><inputtype="range"min="0"max="255"value="255"step="1"id="rRange"/></h2>
<h2><span>G(绿色):</span><spanclass="val"id="gValue">255</span><inputtype="range"min="0"max="255"value="255"step="1"id="gRange"/></h2>
<h2><span>B(蓝色):</span><spanclass="val"id="bValue">255</span><inputtype="range"min="0"max="255"value="255"step="1"id="bRange"/></h2>
<h2><span>O(透明):</span><spanclass="val"id="oValue">1</span><inputtype="range"min="0"max="1"value="1"step="0.1"id="oRange"/></h2>
<h2id="rgb1">RGB(255,255,255)</h2>
<h2id="rgb2">#FFFFFF</h2>
</div>
</body>
<scripttype="text/javascript">
(function(){
varinputNodes=document.getElementsByTagName("input");
varlen=inputNodes.length;
for(vari=0;i<len;i++){
varinputNode=inputNodes[i];
inputNode.index=i;
inputNode.onchange=function(){
varinputVal=inputNodes[this.index].value;
varinputIdAttr=inputNodes[this.index].getAttribute("id");
varspanIdAttr=inputIdAttr.replace("Range","Value");
document.getElementById(spanIdAttr).innerHTML=inputVal;
changeColor();
};
}
functionchangeColor(){
varrgbColor="";
varoColor="#";
for(vari=0;i<len-1;i++){
varinputNode=inputNodes[i];
rgbColor+=rgbColor!=""?",":"";
rgbColor+=inputNode.value;
varn_10=parseInt(inputNode.value);
oColor+=n_10.toString(16).length==1?"0"+n_10.toString(16):n_10.toString(16);
}
vardiv1=document.getElementById("div1");
div1.style.background="RGB("+rgbColor+")";
div1.style.opacity=inputNodes[len-1].value;
varrgb1=document.getElementById("rgb1");
rgb1.innerHTML="RGB("+rgbColor+")";
varrgb2=document.getElementById("rgb2");
rgb2.innerHTML=oColor.toUpperCase();
}
})();
</script>
</html>