js獲取和添加樣式表中的屬性

原生js如何獲取樣式表中的樣式?

js獲取樣式直接能想到的無非就是:

<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			*{margin: 0px;padding: 0px;}
			.box{background-color: aqua;width: 200px;height: 200px;float: left;border:1px solid red;}
			.box::before{content: "";width: 50px;height: 50px;background-color: red;display: block;}
		</style>
	</head>
<body>
		<div class="box"></div>
		<script>
			let width=document.getElementsByClassName("box")[0].style.width;
			console.log(width);//""
		</script>
	</body>

上面輸出輸出的一定是空值,用.style獲取的樣式都是在行內的也就是標籤內,之前想過怎麼解決這個問題,解決辦法就是把樣式寫在行內,又感覺不符合樣式分離規範,上百度搜不巧看到一篇說要寫一個獲取樣式的函數,我一想太麻煩了先跳過沒去多看。
不巧看高性能js的時候發現一個getComputedStyle,可能顯得無知了一些但是幸好我注意到了它。

getComputedStyle

document.defaultView.getComputedStyle(element,pseudoElt)
第一個參數是獲取相對應節點的樣式
第二個參數是pseudoelement僞元素,可選,不是必須可以傳null或不寫。

let dom=document.getElementsByClassName("box")[0];
			let a=document.defaultView.getComputedStyle(dom);
			console.log(a.width);//200px
==================獲取僞元素==============================			
			let a=document.defaultView.getComputedStyle(dom,"::before");
			console.log(a.width);//50px

我是因爲第一次看見defaultView屬性,好奇實驗了一下發現返回的就是window的一部分,使用window.getComputedStyle就可以達到效果爲什麼官方說明大多都是用document.defaultView.getComputedStyle()
原因:
在這裏插入圖片描述
鏈接:傳送
一切爲了兼容

注意

獲取屬性時需要轉換爲小駝峯式寫法例如:

let dom=document.getElementsByClassName("box")[0];
let a=document.defaultView.getComputedStyle(dom);
console.log(a.borderWidth);

還需要注意保留字,例如float儘管chrome是可以實現a.float,任何版本ie都不能使用,但規範規定取floa值時需要像a.cssFloat這樣取值。
還有另一個方法:

let a=document.defaultView.getComputedStyle(dom);
			console.log(a.getPropertyValue("border-width"));

兼容性

IE8使用的是element.currentStyle,所以兼容的話做一個判斷就好:

let a=document.defaultView.getComputedStyle(dom);
if(a){
console.log(a.getPropertyValue("border-width"));
}else{
let dom=document.getElementsByClassName("box")[0].currentStyle;
console.log(dom.borderWidth);
}

在樣式表中添加樣式

示例一個,添加僞類元素樣式,按套路來就好

let styleSheet=document.styleSheets[0];
styleSheet.insertRule(".box::before{content: '';width: 50px;height: 50px;background-color: red;display: block;}",0)

還有一個addRule都說是專屬與IE的,addRule和insertRule的區別是前者默認添加在樣式表的最後,後者是默認在最前面添加,還有傳參略有不同,但是看了MDN看到addRule的是過時的,而且貌似看到一條表達的是IE5-8經過補充後支持insertRule

The below polyfill will correct the input of the arguments of insertRule() to standardize them in Internet Explorer 5–8. It supplements insertRule() with a function that separates the selector from the rules before sending the arguments to the default native insertRul

發佈了32 篇原創文章 · 獲贊 46 · 訪問量 7225
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章