[英]jQuery set CSS color as HEX instead of RGB
我正在嘗試創建一個jQuery掛鈎,該掛鈎將讀取所有顏色並將其設置為十六進制值而不是RGB。 我發現了一個可以正確將顏色讀取為十六進制的鈎子,但是我不確定如何修改它以將CSS顏色寫入十六進制。
因此,例如,我想要$(“ h1”)。css('color','#333333'); 可以使用“ style ='color:#333333;'”(而不是當前的RGB等價)來內聯樣式h1。 我用來返回十六進制讀取顏色的鈎子是:
$.cssHooks.color = {
get: function(elem) {
if (elem.currentStyle)
var bg = elem.currentStyle["color"];
else if (window.getComputedStyle)
var bg = document.defaultView.getComputedStyle(elem,
null).getPropertyValue("color");
if (bg.search("rgb") == -1)
return bg;
else {
bg = bg.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3]);
}
}}
更新
通過將所有元素樣式都轉換為十六進制,然后重建樣式並通過$(elm).attr(style,styles)進行設置,我能夠以超級回旋的方式完成此操作。 似乎很hacky和令人費解,但它可以工作。
該方法似乎對我有用,但是它假定格式正確的字符串。 您可以將檢查添加到此功能:
function rgb_to_hex(rgb_color) {
if (!rgb_color) return ''
return rgb_color
.replace(/.*rgba?\(([^(]+)\).*/gi, '$1')
.split(',')
.splice(0,3)
.reduce(function(acc, cur) { return acc+format_hex(cur) }, '');
}
function format_hex(ns) {
var v;
return isNaN(v = parseInt(ns)) ? '' : ('00' + v.toString(16)).substr(-2);
}
var v,
color1 = (v = rgb_to_hex('rgb(0,0,0)')) !== '' ? '#' + v : '',
color2 = (v = rgb_to_hex('rgb(0,255,0)')) !== '' ? '#' + v : '',
color3 = (v = rgb_to_hex('rgba(123,39,12, .1)')) !== '' ? '#' + v : '',
color4 = (v = rgb_to_hex()) !== '' ? '#' + v : '';
color5 = (v = rgb_to_hex('gobbledegook')) !== '' ? '#' + v : '';
console.log(color1); // '#000000'
console.log(color2); // '#00ff00'
console.log(color3); // '#7b270c'
console.log(color4); // ''
console.log(color5); // ''
另外,此部分:
if (elem.currentStyle)
var bg = elem.currentStyle["color"];
else if (window.getComputedStyle)
var bg = document.defaultView.getComputedStyle(elem, null)
.getPropertyValue("color");
應該是這樣的:
var bg = '';
if (elem.currentStyle) {
bg = elem.currentStyle["color"];
} else if (window.getComputedStyle) {
bg = document.defaultView.getComputedStyle(elem, null)
.getPropertyValue("color");
}
因為可能未定義bg
。
您遇到的問題是jQuery不會寫您想要的東西,但會寫出它能理解的東西。 您可以像這樣“強制”代碼執行所需的操作:
$('h1').css('color', '');
$('h1').attr('style', $('h1').attr('style') + 'color: #FFEE02');
您必須使用第一行才能使html代碼不會增長太多,而在第二行中,請在html上設置顏色。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.