jq css backg,rgb - Can I force jQuery.css("backgroundColor") returns on hexadecimal format? - Stack ...

Colors are always returned as rgb (except IE6 which already returns in hex), then we cannot return in another format natively.

Like you said, you can write a function to convert hex to rgb. Here is a topic with several examples of how to write this function: How to get hex color value rather than RGB value?.

But you wonder if there is a way to directly return the jQuery already in hex: the answer is yes, this is possible using CSS Hooks since jQuery 1.4.3.

The code should be:

$.cssHooks.backgroundColor = {

get: function(elem) {

if (elem.currentStyle)

var bg = elem.currentStyle["backgroundColor"];

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]);

}

}

}

And when you call $(".highlighted").css("backgroundColor"), the return will be #f0ff05. Here is a working sample to you see it working.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值