蝙蝠岛资源网 Design By www.hbtsch.com
本文实例讲述了Javascript实现颜色rgb与16进制转换的方法。分享给大家供大家参考。具体如下:
使用方法:
Color(12,34,56);
Color("#fff")
Color("#defdcd")
实现代码:
//颜色转换
var Color = function() {
if (!(this instanceof Color)) {
var color = new Color();
color._init.apply(color, arguments);
return color;
}
if (arguments.length) {
this._init.apply(this, arguments);
}
}
//设置get,set方法
var methods = ["red", "green", "blue", "colorValue"];
var defineSetGetMethod = function(fn, methods) {
var fnPrototype = fn.prototype;
for (var i = 0; i < methods.length; i++) {
var methodName = methods[i].charAt(0).toLocaleUpperCase() + methods[i].substring(1);
fn.prototype['set' + methodName] = new Function("value", "this." + methods[i] + "= value;");
fn.prototype['get' + methodName] = new Function("return this." + methods[i] + ";");
fn.prototype['toString'] = new Function('return "rgb("+this.red+","+this.green+","+this.blue+")";');
}
};
defineSetGetMethod(Color, methods);
//扩展函数的实例方法
var extend = function(fn, option) {
var fnPrototype = fn.prototype;
for (var i in option) {
fnPrototype[i] = option[i];
}
};
extend(Color, {
_init : function() {
if (arguments.length == 3) {
this.red = arguments[0];
this.green = arguments[1];
this.blue = arguments[2];
this.getColorValue();
} else {
var colorValue = arguments[0].replace(/^\#{1}/, "");
if (colorValue.length == 3) {
colorValue = colorValue.replace(/(.)/g, '$1$1');
}
this.red = parseInt('0x' + colorValue.substring(0, 2), 16);
this.green = parseInt('0x' + colorValue.substring(2, 4), 16);
this.blue = parseInt('0x' + colorValue.substring(4), 16);
this.colorValue = "#" + colorValue;
}
},
getColorValue : function() {
if (this.colorValue) {
return this.colorValue;
}
var hR = this.red.toString(16);
var hG = this.green.toString(16);
var hB = this.blue.toString(16);
return this.colorValue = "#" + (this.red < 16 "0" + hR) : hR) + (this.green < 16 "0" + hG) : hG) + (this.blue < 16 "0" + hB) : hB);
}
});
希望本文所述对大家的javascript程序设计有所帮助。
蝙蝠岛资源网 Design By www.hbtsch.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
蝙蝠岛资源网 Design By www.hbtsch.com
暂无Javascript实现颜色rgb与16进制转换的方法的评论...
更新日志
2025年11月07日
2025年11月07日
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]