Javascript getStyle()
参考文章:
1. 设置元素浮动的几种方式
2.获取css样式表内样式的js函数currentStyle(IE),defaultView(FF)
以下这个方法可以解决以上两种方法中提到的不兼容性问题
var getStyle = function(){
var f = document.defaultView;
return new Function('el', 'style', ["style.indexOf('-')>-1 && (style=style.replace(/-(\\w)/g,function(m,a){return a.toUpperCase()}));", "style=='float' && (style='", f ? 'cssFloat' : 'styleFloat', "');return el.style[style] || ", f ? 'window.getComputedStyle(el, null)[style]' : 'el.currentStyle[style]', ' || null;'].join(''));
}();
test:
function getStyleTest(){
var nav = document.getElementsByTagName("nav");
alert(getStyle(nav[0], "margin-top"));
alert(getStyle(nav[0], "float"));
alert(getStyle(nav[0], "color"));
}
从RGB转化成16进制:
function getHexFromRGB(rgb){
var regexp = /^rgb\(([0-9]{0,3})\,\s([0-9]{0,3})\,\s([0-9]{0,3})\)/g;
var re = rgb.replace(regexp, "$1 $2 $3").split(" ");//利用正则表达式去掉多余的部分
var hexColor = "#";
var hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
for (var i = 0; i < 3; i++) {
var r = null;
var c = re[i];
var hexAr = [];
while (c > 16) {
r = c % 16;
c = (c / 16) >> 0;
hexAr.push(hex[r]);
}
hexAr.push(hex[c]);
hexColor += hexAr.reverse().join('');
}
return hexColor;
}
4.修改CSS规则:
参考:DOM StyleSheet Object http://www.javascriptkit.com/domref/stylesheet.shtml
<script type="text/javascript">
window.onload = function(){
var cssRules = document.styleSheets[0].rules ? document.styleSheets[0].rules : document.styleSheets[0].cssRules;
cssRules[1].style.fontSize = "23px";
for(var ex in cssRules[1]){
console.log(ex);
}
alert(cssRules[0].type);
alert(cssRules[0].cssText);
alert(cssRules[0].selectorText);
}
</script>