如果製作一個RGB色碼轉換器,算是考驗操作DOM!
那把它分成三個目標來依序完成,
- 抓slider的數字,存放在每個滑塊右邊的格子
- 透過
slider.addEventListener("input", function (event) {...})
監聽滑塊變動事件。 - 當事件被觸發時,取得事件目標元素,就是滑塊
let target = event.target
- 獲得滑塊的當前值
let inputValue = target.value
- 找到與該滑塊相鄰的 span 元素
let valueBox = target.nextElementSibling
- 將滑塊的值顯示在相鄰的 span 元素中
valueBox.textContent = inputValue
- 再slider的數字轉換成十六進位並顯示於下面的格子
- 根據滑塊的 ID
#rgb-r
、#rgb-g
、#rgb-b
,確定是哪個滑塊的值被改變。 - 將該滑塊的數值轉換成十六進位。若數值小於 16,則在前面補 0 以確保每個數值都是兩位數
hex[0] = "0" + Number(target.value).toString(16)
或hex[0] = Number(target.value).toString(16)
等 - 更新對應的十六進位數值陣列
hex
中的值。 - 組合成完整的十六進位色碼字串
newHexCode = "#" + hex[0] + hex[1] + hex[2]
- 將十六進位色碼顯示在頁面下方的大格子中
hexCode.textContent = newHexCode
3. background-color會監聽格子裡的RGB色碼而改變
- 在更新 HEX 色碼字串後,將色碼設置為頁面的背景顏色
document.body.style.backgroundColor = hexCode.textContent
以下示範請看~~

<body>
<div class="slider">
<h1> RGB to HEX </h1>
<div>
<span class="red"> R </span>
<input type="range" id="rgb-r" name="rgb-r" min="0" max="255" value="0">
<span class="red" id="red"> 0 </span>
</div>
<div>
<span class="green">G</span>
<input type="range" id="rgb-g" name="rgb-g" min="0" max="255" value="0">
<span class="green" id="green"> 0 </span>
</div>
<div>
<span class="blue">B</span>
<input type="range" id="rgb-b" name="rgb-b" min="0" max="255" value="0">
<span class="blue" id="blue"> 0 </span>
</div>
<div>
<h1 class="hexCode">#000000</h1>
</div>
</div>
<body>
body {
font-family: "Roboto", sans-serif;
background-color: black;
font-weight: bold;
}
nav {
padding-top: 10px;
font-size: 20px;
}
.slider {
height: 500px;
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
}
.red {
border-radius: 20%;
padding: 10px;
background-color: red;
}
.green {
padding: 10px;
background-color: green;
border-radius: 20%;
}
.blue {
padding: 10px;
background-color: blue;
border-radius: 20%;
}
h1 {
color: #ffffff;
background-color: rgba(210, 155, 155, 0.5);
border: 2px solid #000000;
border-radius: 8px;
margin: 10px 10px;
padding: 5px 30px;
}
const slider = document.querySelector(".slider");
const hexCode = document.querySelector(".hexCode");
let newHexCode = "";
let hex = ["00", "00", "00"];
slider.addEventListener("input", function (event) {
let target = event.target;
let inputValue = target.value;
let valueBox = target.nextElementSibling; // 滑塊後的 span
valueBox.textContent = inputValue;
if (target.matches("#rgb-r")) {
if (target.value < 16) {
hex[0] = "0" + Number(target.value).toString(16);
} else {
hex[0] = Number(target.value).toString(16);
}
} else if (target.matches("#rgb-g")) {
if (target.value < 16) {
hex[1] = "0" + Number(target.value).toString(16);
} else {
hex[1] = Number(target.value).toString(16);
}
} else {
if (target.value < 16) {
hex[2] = "0" + Number(target.value).toString(16);
} else {
hex[2] = Number(target.value).toString(16);
}
}
newHexCode = "#" + hex[0] + hex[1] + hex[2];
hexCode.textContent = newHexCode;
document.body.style.backgroundColor = hexCode.textContent;
});