從零開始的全棧工程師——js篇2.16
阿新 • • 發佈:2018-11-13
js操作css樣式
div.style.width=“200px” 在div標籤內我們添加了一個style屬性 並設定了width值 這種寫法會給
標籤帶來了大量的style屬性 跟實際專案是不符的 我們沒有讓css和html分離
所以如果只是為了獲取css樣式
window.getComputedStyle() 獲取經過計算機計算的所有屬性
就是隻要渲染出來的都是經過計算的。
1.window.getComputedStyle() (只讀)
寫法:window.getComputedStyle() ie678寫法:aa.currentStyle
↑↑↑獲取經過計算機計算的所有屬性(只要渲染出來的 都是經過計算的)(ie678不支援這個方法)
兩個引數 第一個引數是當前元素 第二個一般寫成null 並且這個方法是隻讀的
2.try{
}catch(error){} 不報錯執行try裡面的程式碼塊,報錯執行catch裡面的程式碼塊。
前提條件是報錯,如果不是報錯不能使用
var csss;
try{
csss=window.getComputedStyle(aa,null)
}catch(e){
csss=aa.currentStyle
}
console.log(csss)
總結:
Js解決相容的方法
1. ||
Var dd=document.documentElement.clientWidth||document.body.clientWidth
2. if()else{}
if(window.getComputedStyle){
csss=window.getComputedStyle(aa,null)
}else{
csss=aa.currentStyle
}
console.log(csss)
3.try{} catch(err){}
必須在報錯的條件下,和if else比較效能上比較差,不在萬不得以的情況下不使用