碰到一个题:获取非行间样式的方法。(先写了小的demo)
1.html文件
<head> <style> #test { font-size: 14px; line-height: 20px; padding: 10px; border: 1px solid #ccc; } </style> </head> <body> <div id="test" style='color:#f00;'>我的样式</div> </body>
2. js
1 console.log(document.getElementById('test').style.color); 2 /* 3 1. 把颜色的值写在style标签里的时候,console.log值为空; 4 2. 把颜色写在行内样式里时,console的值为 rgb(255, 0, 0) 5 所以,这样可以看到,document.getElementById('test').style.XXX只能拿到行内的style样式,而不能拿到内嵌的样式 6 */
function getStyle(obj, attr, value) { if (!value) {//是否set属性值 return window.getComputedStyle ? window.getComputedStyle(obj, false)[attr] : obj.currentStyle[attr]; //currenStyle兼容IE,getComputedStyle兼容FF,Chrome(FF未测试) } else { obj.style[attr] = value } } getStyle(document.getElementById('test'), 'color', '#a34e3f'); //如果set属性值,则写出第三个参数,如果不set的话,不写第三个参数