前言
说到js获取元素样式,大家肯定首先想到 元素.style。但是通过element.style只能获取元素的内联样式,也就是写在元素style里的样式,无法取到元素的最终样式,包括内联样式、嵌入样式和外部样式。
方法
想要获取元素最终样式,需要使用以下两种方法:
const el = document.getElementById("#el")
//IE
console.log(el.currentStyle.width)
//其他浏览器
console.log(getComputedStyle(el,[null]))
1. 元素.currentStyle.样式名
只有ie8以及以上能用,如果获取的样式没有定义,返回值为默认值
2. getComputedStyle(元素,[伪类名])(除ie以外浏览器)
2个参数:元素节点 & 伪类
如果获取的样式没有定义,返回值为实际值。比如:
一个div的height设置为auto,内部元素100px,撑起div
currentStyle.height 返回值为auto
getComputedStyle(el)取到的height为100px (就是实际高度)
相同点:两种方式取到的值都是 只读 的,无法设置样式
想要设置样式需要通过 元素.style.样式名
定义函数来兼容
/* 参数为3个,
第一个必传,是要获取样式的元素节点
第二个可选,是要获取样式的元素节点的伪类
第三个可选,是要获取的样式名,比如width
*/
function getStyles({ el, pseudoClass = null, styleName }) {
if (!el) {
console.error("调用getStyles时未传入要获取的元素节点,或传入值为空")
return
}
if (window.getComputedStyle && !styleName) { //非ie获取全部样式
return getComputedStyle(el, [pseudoClass])
}
if (window.getComputedStyle && styleName) { //非ie获取单个样式
return getComputedStyle(el, [pseudoClass])[styleName]
}
if (!window.getComputedStyle && !styleName) { //ie获取全部样式
return el.currentStyle
}
if (!window.getComputedStyle && styleName) { //ie获取单个样式
return el.currentStyle[styleName]
}
}
//调用方法
getStyles({
el: document.getElementById('el'),
pseudoClass: 'before',
styleName: 'width'
})
如果有帮到你的话就帮忙点个赞吧!!