您的位置:首页 > 教程笔记 > 前端笔记

将十六进制颜色值转换为RGB颜色值代码实例

2023-12-04 13:39:35 前端笔记 29

本章节分享一段代码实例它能够实现将十六进制颜色值转换为RGB颜色值代码实例。

如果从RGB颜色值转换为十六进制颜色值可以参阅jQuery如何将获取的颜色值转换为十六进制形式一章节。

代码实例:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="/" />
<title>实例</title>
<style>
*{
  margin:0;
  padding:0;
  font-family:'Microsoft yahei'
}
.replace{
  width:400px;
  height:210px;
  margin:0 auto;
  padding-top:40px;
}
.title{
  text-align:center;
  display:block
}
form{
  width:200px;
  margin:30px auto;
}
input{outline:none;}
input[type="button"]{
  cursor:pointer;
}
</style>
<script>
function hexToR(h){
  return parseInt((cutHex(h)).substring(0, 2), 16)
}
function hexToG(h) {
  return parseInt((cutHex(h)).substring(2, 4), 16)
}
function hexToB(h) {
  return parseInt((cutHex(h)).substring(4, 6), 16)
}
function cutHex(h) {
  return h.charAt(0) == "#" ? h.substring(1, 7) : h
}
function setBgColorById(id, sColor) {
  var elems;
  if (document.getElementById) {
    if (elems = document.getElementById(id)) {
      if (elems.style) elems.style.backgroundColor = sColor;
    }
  }
}
window.onload=function(){
  var obt=document.getElementById("bt");
  obt.onclick=function(){
    setBgColorById('colorSample',this.form.hex.value);
    this.form.r.value=hexToR(this.form.hex.value);
    this.form.g.value=hexToG(this.form.hex.value);
    this.form.b.value=hexToB(this.form.hex.value);
  }
}
</script>
</head>
<body>
  <div class="replace"> 
  <span class="title">javascript原生16进制颜色值转RGB值</span>
  <form name="rgb">
    <input value="ffffff" maxlength="7" size="16" name="hex" />
    <input id="bt" value="转换" type="button" name="btn"/><br /><br />
    R:<input style="width:30px" size="3" name="r" />
    G:<input style="width:30px" size="3" name="g" />
    B:<input style="width:30px" size="3" name="b" />
  </form>
  </div>
</body>
</html>

相关推荐