原生JS获取内嵌,外部css样式,使用style只能直接获取内联style的属性值

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JS原生获取style属性值</title>
    <style>
        #div {
            width: 200px;
            height: 200px;
            background-color: #ff00ff;
            border: 20px solid #ffff00;
            margin: 30px auto;
            padding-top: 100px;
            font-size: 30px;
            text-align: center;
        }
        #div:after{
              content: ':after';
              display: block;
        }
    </style>
    <script src="http_code.jquery.com_jquery-2.0.0.js"></script>
</head>
<body>

<div id="div" style='display: block;'>
    JS原生获取style属性值
</div>


<script>

   var div=document.getElementById('div');
   var $div=$('#div');
      
   window.onload=function(){
      //console.log(div.style)
      //style();
      
      //不同浏览器,显示效果不同
      GetComputedStyle();
      
      //IE自己
      //CurrentStyle();
      
      //hacker()
   }
   
   //原生js直接使用style属性获取css样式
   function style(){
      //返回CSSStyleDeclaration对象,是一个属性集合,里面的属性的值都为空
      console.log(div.style)
      
      //直接使用style属性无法访问到内嵌,外部的css样式,只能访问内联样式的css样式
      console.log('内嵌,外部width.....'+div.style.width)
      console.log('内联display.....'+div.style.display)
      
      //直接使用jq获取css的样式
      console.log('jq.....'+$div.css('width'))
   }
   
   function GetComputedStyle(){
      
      // window.getComputedStyle(Obj,Pseudo-classes).property
      
      var gcs=window.getComputedStyle(div,null);
      var gcs_a=window.getComputedStyle(div,'after');
      
      //console.log('gcs_a.....'+gcs_a.display)
      
      //返回CSSStyleDeclaration对象,有值的,是只读的
      console.log(gcs)
   
      //使用getComputedStyle获取内嵌,内联,外部的css样式
      console.log('gcs.....'+gcs.width)
      //多属性的样式下chrome能获取,firefox获取不到
      console.log('border....'+gcs.border)
      console.log('borderColor....'+gcs.borderColor)
      console.log('paddingTop....'+gcs.paddingTop)
      
      //jq使用的css选择器同理
      console.log('$border.....'+$div.css('border'))
      console.log('$borderColor....'+$div.css('border-color'))
   
   }

   function CurrentStyle(){
      
      Obj.currentStyle.property
      
      div.currentStyle.width
      
   }
   
   function hacker(){
      
      if(window.getComputedStyle){
         
         GetComputedStyle()
         
      }else if(Object.currentStyle){
         
         CurrentStyle()
         
      }else {
         return false
      }
      
   }
   
</script>
</body>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值