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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值