我有这个函数使用cssHooks将背景颜色的rgb颜色转换为HEX值。我的问题是,我也想做边框颜色和文字颜色。我是否需要创建3个单独的功能,还是可以组合使用?
编辑:所以这里有3个功能。我很难将所有三个组合成一个 - 以使代码更清晰。如何将所有3个组合成一个钩子?
$.cssHooks.backgroundColor = {
get: function(elem) {
if (elem.currentStyle)
var bg = elem.currentStyle["background-color"];
else if (window.getComputedStyle)
var bg = document.defaultView.getComputedStyle(elem,
null).getPropertyValue("background-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]);
}
}
}
$.cssHooks.borderColor = {
get: function(elem) {
if (elem.currentStyle)
var bg = elem.currentStyle["border-color"];
else if (window.getComputedStyle)
var bg = document.defaultView.getComputedStyle(elem,
null).getPropertyValue("border-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]);
}
}
}
$.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]);
}
}
}
答案 0 :(得分:0)
这会更改所有值输入...而不仅仅是单个CSS选择器......
$.cssHooks.colorz = {
get: function(elem, rule) {
if (elem.currentStyle)
var bg = elem.currentStyle[rule];
else if (window.getComputedStyle)
var bg = document.defaultView.getComputedStyle(elem,
null).getPropertyValue(rule);
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]);
}
}
}
答案 1 :(得分:0)
你可以这样做:
function _register_jquery_get_hex_color(newname,styleattr) {
$.cssHooks[newname] = {
get: function(elem) {
if (elem.currentStyle)
var bg = elem.currentStyle[styleattr];
else if (window.getComputedStyle)
var bg = document.defaultView.getComputedStyle(elem,
null).getPropertyValue(styleattr);
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]);
}
}
}
}
_register_jquery_get_hex_color("backgroundColor","background-color");
_register_jquery_get_hex_color("borderColor","border-color");
_register_jquery_get_hex_color("color","color");