打印选定 dom 的样式时,它会以字典形式显示,其中包含值“ ”,即使我已经使用样式标签指定了它
2020-08-18
220
我的 style 标签有
<style>
#armsblue{
position:absolute;
left:0.33vw;
top:-0.3vw;
z-index: -1;
}
</style>
body 标签有:
<img src="E:\graphics\torsoblue.png" alt="Girl in a jacket" width="80%" id="torsoblue">
<img src="E:\graphics\armsblue.png" alt="Girl in a jacket" width="80%" id="armsblue">
打印带有 armsblue id 的 img dom 的 javascript:
torsos=document.querySelectorAll("#torsoblue,");
console.log(torsos[0].style);
输出显示在控制台上:
CSSStyleDeclaration {alignContent: "", alignItems: "", alignSelf: "", alignmentBaseline: "", all: "", …}
当您展开它并检查字典时,即使我将这些值放在标签内,字典中也有 position: "" 、 zIndex: "" 等等。
1个回答
在这种情况下,您想要从样式表访问 CSS 属性,这需要使用
window.getComputedStyle
,否则,如果这些属性在内联使用(如
#torsoblue
示例中所示),则可以使用
HTMLElement.style
。
const torsos = document.querySelectorAll('#torsoblue');
console.log(torsos[0].style.position);
console.log(torsos[0].style.left);
console.log(torsos[0].style.top);
console.log(torsos[0].style.zIndex);
const armsblueEl = document.getElementById('armsblue');
const computedStyle = window.getComputedStyle(armsblueEl);
console.log(computedStyle.position);
console.log(computedStyle.left);
console.log(computedStyle.top);
console.log(computedStyle.zIndex);
#armsblue {
position: absolute;
left: 0.33vw;
top: -0.3vw;
z-index: -1;
}
<img src="#" alt="Girl in a jacket" width="80%" id="torsoblue"
style="position: relative;left: 0.66vw;top:-0.6vw;z-index: -2">
<img src="#" alt="Girl in a jacket" width="80%" id="armsblue">
Buczkowski
2020-08-18