使用Javascript获取HTML元素样式

问题描述 投票:1回答:3

我正在尝试检索HTML元素的backgroundColor。但是当我用js检查样式时,一切都是空的或未定义的。但是当我在开发者控制台上检查这个元素时,我可以看到有一个backgroundColor。我无法理解什么是错的。你有什么提示会导致这个问题吗?

document.getElementById("id1").style

JS get style result

Developer console

javascript html reactjs dom
3个回答
4
投票

使用window.getComputedStyle

阅读更多https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

基本上style属性只读取元素上的内联样式


1
投票

试试getComputedStyle

window.getComputedStyle(document.getElementById("id1"));

1
投票

您应该尝试使用window.getComputedStyle方法获取应用的样式。

let element = document.getElementById("id1");
window.getComputedStyle(element);
© www.soinside.com 2019 - 2024. All rights reserved.