Code
< script type ="text/javascript" >
/*
*由于firefox在返回一个元素的color的时候往往是返回一个字符串比如rgb(255, 255, 255)
*而IE往往返回#FFFFFF这种形式,在有时候做颜色判断时很难做比较,于是我便写了这个函数
*方便从一个含有三个颜色值的字符串转换为一个Hex的颜色值
*/
String.prototype.hexColor = function (){
if ( this .indexOf( " # " ) >= 0 ) return this ; // 如果是一个hex值则直接返回
var pattern = new RegExp( " 2[0-4]\\d|25[0-5]|[01]?\\d\\d? " , " ig " ); // 这个正则是取 0 ~ 255的数字
var va = this .match(pattern);
if (va.length != 3 ) return " NaN " ; // 取出的数组长度一定得为3
var result = " # " ;
for ( var i = 0 ; i < 3 ; i ++ ) {
var num = parseInt(va[i]);
result += num < 16 ? " 0 " + num.toString( 16 ) : num.toString( 16 ); // 如果小于F在前面补0
}
return result;
}
/* ****************测试开始********************** */
var a = " rgb(255, 254, 253) " ;
var b = " 255,254,253 " ;
var c = " 256,254,253 " ;
var d = " #ff36ff " ;
start = new Date().getTime();
document.write(a.hexColor() + " <br /> " + b.hexColor() + " <br /> " + c.hexColor() + " <br /> " + d.hexColor())
end = new Date().getTime();
document.write( " <br />耗时: " + (end - start) + " ms " );
/* ****************测试结束********************** */
</ script >
< script type ="text/javascript" >
/*
*由于firefox在返回一个元素的color的时候往往是返回一个字符串比如rgb(255, 255, 255)
*而IE往往返回#FFFFFF这种形式,在有时候做颜色判断时很难做比较,于是我便写了这个函数
*方便从一个含有三个颜色值的字符串转换为一个Hex的颜色值
*/
String.prototype.hexColor = function (){
if ( this .indexOf( " # " ) >= 0 ) return this ; // 如果是一个hex值则直接返回
var pattern = new RegExp( " 2[0-4]\\d|25[0-5]|[01]?\\d\\d? " , " ig " ); // 这个正则是取 0 ~ 255的数字
var va = this .match(pattern);
if (va.length != 3 ) return " NaN " ; // 取出的数组长度一定得为3
var result = " # " ;
for ( var i = 0 ; i < 3 ; i ++ ) {
var num = parseInt(va[i]);
result += num < 16 ? " 0 " + num.toString( 16 ) : num.toString( 16 ); // 如果小于F在前面补0
}
return result;
}
/* ****************测试开始********************** */
var a = " rgb(255, 254, 253) " ;
var b = " 255,254,253 " ;
var c = " 256,254,253 " ;
var d = " #ff36ff " ;
start = new Date().getTime();
document.write(a.hexColor() + " <br /> " + b.hexColor() + " <br /> " + c.hexColor() + " <br /> " + d.hexColor())
end = new Date().getTime();
document.write( " <br />耗时: " + (end - start) + " ms " );
/* ****************测试结束********************** */
</ script >