壹 ❀ 引
我們知道書寫css有三種做法,它們分別是行內樣式,內嵌樣式和外部引用。我們來看個例子,下面這個div分別通過內部樣式添加了顏色,內嵌樣式添加了字體大小,外部引入樣式添加了寬度。
<!-- 行內樣式 --> <div style="color: red;">聽風是風</div> <!-- 內嵌樣式 --> <style> div { font-size: 24px; } </style> <!-- 外部引入 --> <link rel="stylesheet" href="style/demo.css"> /* demo.css */ div{ width: 100px; }
現在我們來嘗試獲取這個div的樣式,使用JavaScript寫法:
let div = document.querySelector("div"); console.log(div.style.color);//red console.log(div.style.fontSize);//空 console.log(div.style.width);//空
事實證明,通過style屬性只能訪問到行內樣式,內嵌以及外部引用都無法讀取,怎么辦呢?我們可以使用 getComputedStyle 方法。
貳 ❀ 解決方案
還是上面的例子,我們使用getComputedStyle方法,直接上代碼:
let div = document.querySelector("div"); let style = window.getComputedStyle(div, null); console.log(style['color']); //rgb(255, 0, 0) console.log(style['fontSize']); //24px console.log(style['width']); //100px
看,不管以何種方式設置的樣式,getComputedStyle方法都能輕松幫你拿到,這個方法是個什么意思呢?我們來說說這個方法。
叄 ❀ 關於getComputedStyle方法
一個完整的getComputedStyle方法其實是這樣:
let style = window.getComputedStyle(element, [pseudoElt]);
其中 element 是你需要獲取style 的元素;我們知道元素能通過after與before設置偽元素(注意是偽元素不是偽類),pseudoElt就是用於獲取偽元素樣式,如果不需要請將此參數設置為null。返回的style是一個屬性鍵值對的合集,是一個對象,我們可以通過屬性名直接訪問對應的值,或者通過 getPropertyValue 方法獲取,我們來看一個帶有偽元素的例子:
<input type="text" class="demo">
/* demo.css */ input { outline: none; border: 1px solid #ddd; } input::after { content: ""; border: 2px solid #e4393c; }
var input = document.querySelector(".demo"); var border = window.getComputedStyle(input, null)['border']; console.log(border); //1px solid rgb(221, 221, 221) //等同於 var border = window.getComputedStyle(input, null).getPropertyValue("border"); console.log(border); //1px solid rgb(221, 221, 221) //獲取偽元素 var border = window.getComputedStyle(input, '::after')['border']; console.log(border); //2px solid rgb(228, 57, 60) //等同於 var border = window.getComputedStyle(input, '::after').getPropertyValue("border"); console.log(border); //2px solid rgb(228, 57, 60)
我們來看看此方法的兼容性:
兼容性非常優秀,IE都完美兼容到了9以上,可能有人就要問了,要是我低版本IE也要獲取非行內樣式怎么辦?其實早版本的IE也有專門提供一個屬性 currentStyle,它的使用是這樣:
var style = element.currentStyle[prop];
此屬性的兼容性如下圖:
可以看到從兼容性來說,這兩個屬性方法完美的互補了IE兼容情況,注意,如果不考慮低版本IE,請直接使用 getComputedStyle 方法。
肆 ❀ 一個通用樣式獲取/設置方法
直接上代碼:
/** * @desc 一個用於設置和獲取css樣式的方法 * @param {*} ele element元素 * @param {*} prop 樣式名 * @param {*} val 樣式值 */ function css(ele, prop, val) { if (val) { // 設置css屬性 ele.style[prop] = val; } else { // 兼容低版本IE if (ele.currentStyle) { return ele.currentStyle[prop]; } else { return window.getComputedStyle(ele, null)[prop]; }; }; };
那么關於獲取非行內樣式就說到這里了,還有一小時跨年,新年快樂。2020年也要加油!