JS如何获取和修改CSS伪类属性

2,003 阅读2分钟

DOM操作是操作HTML文档,那么js如何与CSS相联系,标题是小编所要说的重点,但是先总结一下JS如何读取标签CSS属性方法,直接看的话可以去看第三点。

  • 对象.style.属性

    这种方法只能读取行间的CSS属性,但他特别在通过js只能采取这种方法去改变标签样式(也是相当于在行间加属性值),所以可以看出行间样式优先级大于写在CSS中(除非在属性后加上 !important)

  • window.getComputedStyle(对象,null).属性

    这个方法就是相当于获取“真实”对象属性,实际页面中是多少就是多少。像这样我们直接输出div.style.height就是行间的值200px,在控制台打印window.getComputedStyle(div,null).height就会输出100px。

    <style>
          *{
              margin:0;
              padding:0;
          }
          div{
              width: 100px;
              height: 100px !important;
              background-color: red;
          }
      </style>
      <body>
          <div style="height: 200px"></div> 
          <script>
              var div=document.getElementsByTagName('div')[0];
              console.log(div.style.height);
          </script>
      </body>
    
  • 如何获取伪类CSS属性

    重点小编是想补充一下这个伪类可以说是完全属于CSS中产生的,我们同样可以通过window.getComputedStyle方法实现。

    div{
        width: 100px;
        height: 100px !important;
        background-color: red;
    }
    div::before{
        content: "123";
        background-color: #fff;
    }
    

    返回结果如下:

    Alt text
    那么同时一般的伪类属性在js之中通过修改类名去更改,为了避免代码的耦合所以讲盒子自身属性以行内式书写。

    看实例:

    <style>
        .white::before{
            content: "123";
            background-color: #fff;
        }
        .orange::before{
            content: "123";
            background-color: orange;
        }
    </style>
    </head>
    <body>
        <div class="white" style="height: 100px; width: 100px; background-color: red;"></div> 
        <script>
            var div=document.getElementsByTagName('div')[0];
            div.onclick=function(){
                div.className="orange";
            }
        </script>
    </body>