DOM操做是操做HTML文檔,那麼js如何與CSS相聯繫,標題是小編所要說的重點,可是先總結一下JS如何讀取標籤CSS屬性方法,直接看的話能夠去看第三點。javascript
對象.style.屬性css
這種方法只能讀取行間的CSS屬性,但他特別在經過js只能採起這種方法去改變標籤樣式(也是至關於在行間加屬性值),因此能夠看出行間樣式優先級大於寫在CSS中(除非在屬性後加上 !important)html
window.getComputedStyle(對象,null).屬性java
這個方法就是至關於獲取「真實」對象屬性,實際頁面中是多少就是多少。像這樣咱們直接輸出div.style.height就是行間的值200px,在控制檯打印window.getComputedStyle(div,null).height就會輸出100px。ui
<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屬性spa
重點小編是想補充一下這個僞類能夠說是徹底屬於CSS中產生的,咱們一樣能夠經過window.getComputedStyle方法實現。code
div{
width: 100px;
height: 100px !important;
background-color: red;
}
div::before{
content: "123";
background-color: #fff;
}
複製代碼
返回結果以下: cdn
看實例:htm
<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>
複製代碼