javascript获取style兼容性问题

获取css 样式的方法有三种 : style, currentStyle , getComputedStyle

style  (无兼容性问题)

  获取语法: ele.style.attr ; 设置语法:ele.style.attr = '值'

  大多数情况下,javascript中获取和设置style样式都是通过类似" div.style.fontSize" 的方式 , 但是该方式只能获取行内样式 , 即通过link或者<style>引入的样式无法获取, 如行内没设置样式, 返回为空值。

currentStyle (支持IE, 不支持FF和Chrome)

  语法 ele.cureentStyle.attr或者 ele.currentStyle[attr]

  当在script中打印 console.log(div.currentStyle)时, 在IE上输出[object Object], 而在Chrome中输出undefined, console.log(window.getComputedStyle)则相反.

getComputedStyle (支持FF和Chrome,不支持IE)

  语法 window.getComputedStyle(ele, null).attr 或者  window.getComputedStyle(ele, null)[attr]

解决currentStyle和getComputedStyle的兼容性问题, 注意,两者都只能获取css而不能设置css

 function getStyle (ele, styleName) {
if (window.getComputedStyle) {
return window.getComputedStyle(ele, null)[styleName]
} else {
return ele.currentStyle[styleName]
}
} // 调用
getStyle(div, 'fontSize')
上一篇:Asp.net Core AOP实现(采用Autofac)


下一篇:.net core AOP之Filter