gpt4 book ai didi

javascript - 如何在 Javascript 中获取 CSS 类属性?

转载 作者:技术小花猫 更新时间:2023-10-29 11:49:23 25 4
gpt4 key购买 nike

.test {
width:80px;
height:50px;
background-color:#808080;
margin:20px;
}

HTML -

<div class="test">Click Here</div>

在 JavaScript 中我想得到 margin:20px

最佳答案

对于现代浏览器,您可以使用 getComputedStyle :

var elem,
style;
elem = document.querySelector('.test');
style = getComputedStyle(elem);
style.marginTop; //`20px`
style.marginRight; //`20px`
style.marginBottom; //`20px`
style.marginLeft; //`20px`

margin 是一种复合样式,跨浏览器不可靠。 -top -right-bottom-left 中的每一个都应单独访问。

fiddle

关于javascript - 如何在 Javascript 中获取 CSS 类属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20377835/

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