• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
骑着小毛驴过冬的八阿哥
博客园    首页    新随笔    联系   管理    订阅  订阅

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

 1 function getStyle (ele, styleName) {
 2     if (window.getComputedStyle) {
 3        return window.getComputedStyle(ele, null)[styleName]          
 4     } else {
 5        return ele.currentStyle[styleName]
 6     }
 7 }
 8 
 9 // 调用
10 getStyle(div, 'fontSize')

 

posted @ 2018-07-04 22:30  浅草马甲  阅读(215)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3