gpt4 book ai didi

javascript - 使用javascript从css文件中获取元素的样式

转载 作者:太空宇宙 更新时间:2023-11-03 22:34:37 24 4
gpt4 key购买 nike

我想用 javascript 从 css 文件中获取元素的样式。但是,我只能获取在 javascript 上输入样式属性的元素。我在 Angular 上这样尝试过;

angular.element(document.getElementById("box")).css("width")

没用。之后,我这样试过;

document.getElementById("box").style

但是没有用。我怎样才能做到这一点?

最佳答案

这不是 Angular 的问题,而是 CSS 和 Javascript 交互的方式。您需要使用 getComputedStyle 来读取 CSS 文件中定义的样式属性。

// This will work (because it's an inline style)
console.log(document.getElementById('a').style.width)

// This won't work (because the style was defined in css):
console.log(document.getElementById('b').style.width)

// getComputedStyle will work regardless of the source:
console.log(window.getComputedStyle(document.getElementById('b')).width)
#b {width: 100px}
<div id="a" style="width: 100px">A</div>
<div id="b">B</div>

关于javascript - 使用javascript从css文件中获取元素的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47024065/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com