我正在嘗試使用變數進行從 rgb 到十六進制的轉換。
而不是我想要的最后一行
var rgbnhcp1 = rgbToHex(nhcp1)
后來用它寫在一個div
document.getElementById("TextWithRgbValue").innerHTML = rgbnhcp1;
問題是您必須在上面的代碼中放置就緒值,例如 rgb 20,45,233 而不是變數,以便稍后使用它將其放入 div 中。你能幫忙嗎?
// Variables - taking color property in rgb from css classes
var nhcp1 = window.getComputedStyle(document.querySelector(".nhcp1"), null).getPropertyValue('background-color');
var nhcp2 = window.getComputedStyle(document.querySelector(".nhcp2"), null).getPropertyValue('background-color');
var nhcp3 = window.getComputedStyle(document.querySelector(".nhcp3"), null).getPropertyValue('background-color');
var nhcp4 = window.getComputedStyle(document.querySelector(".nhcp4"), null).getPropertyValue('background-color');
var nhcp5 = window.getComputedStyle(document.querySelector(".nhcp5"), null).getPropertyValue('background-color');
// RGB to HEX
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" hex : hex;
}
function rgbToHex(r, g, b) {
return "#" componentToHex(r) componentToHex(g) componentToHex(b);
}
console.log(rgbToHex(0, 51, 255)); // #0033ff
.nhcp4 { bakground-color:teal}
.nhcp5 { bakground-color:yellow}
<div class="nhcp1" style="background-color:red">Div 1</div>
<div class="nhcp2" style="background-color:blue">Div 2</div>
<div class="nhcp3" style="background-color:green">Div 3</div>
<div class="nhcp4">Div 4</div>
<div class="nhcp5">Div 5</div>
uj5u.com熱心網友回復:
原因是,你的
var nhcp1 = window.getComputedStyle(document.querySelector(".nhcp1"), null).getPropertyValue('background-color');
正在將字串加載"rgb(x, y, z)"到變數中nhcp1。
但是,您的函式rgbToHex(a, b, c)需要 3 個整數引數。
因此,您需要做的就是從該nhcp1字串中提取 3 個整數并將其輸入到函式中。
這個答案將幫助您提取具有 rgb 值作為字串的物件。
uj5u.com熱心網友回復:
您需要從 rgb(a) 字串中提取 3 個值
注意我忽略了可能的透明度
// RGB to HEX
const componentToHex = c => ( c).toString(16).padStart(2,"0").toUpperCase();
const rgbToHex = (rgb) => {
const [r, g, b] = rgb.split(",");
return "#" componentToHex(r) componentToHex(g) componentToHex(b)
};
const getRgb = selector => window.getComputedStyle(document.querySelector(selector), null).getPropertyValue('background-color').match(/(\d , \d , \d )/)[1]
console.log(rgbToHex(getRgb(".nhcp1")));
console.log(rgbToHex(getRgb(".nhcp2")));
console.log(rgbToHex(getRgb(".nhcp3")));
console.log(rgbToHex(getRgb(".nhcp4")));
console.log(rgbToHex(getRgb(".nhcp5")));
.nhcp4 {
background-color: teal
}
.nhcp5 {
background-color: rgba(211, 0, 211, 0.5)
}
<div class="nhcp1" style="background-color:red">Div 1</div>
<div class="nhcp2" style="background-color:blue">Div 2</div>
<div class="nhcp3" style="background-color:green">Div 3</div>
<div class="nhcp4">Div 4</div>
<div class="nhcp5">Div 5</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/320778.html
標籤:javascript 变量 十六进制 RGB 转换器
上一篇:使用變數更改頁面背景
下一篇:Linux -查找功能
