如果製作一個RGB色碼轉換器,算是考驗操作DOM!
那把它分成三個目標來依序完成,
slider.addEventListener("input", function (event) {...})
監聽滑塊變動事件。let target = event.target
let inputValue = target.value
let valueBox = target.nextElementSibling
valueBox.textContent = inputValue
#rgb-r
、#rgb-g
、#rgb-b
,確定是哪個滑塊的值被改變。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色碼而改變
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;
});