我 2 天前问过一个关于 Stack overflow 的问题。 How can I get all the properties from the class or id on click using jQuery?
我只是想知道为什么这段代码在 Firefox、Safari 和 Edge 中无法正常运行,我该如何修复它。
$(".sample").click(function() {
var html = [],
x = $(this).css([
"margin", "padding", "color", "border"
]);
$.each(x, function(prop, value) {
html.push(prop + ": " + value);
});
$("#result").html(html.join("<br>"));
})
关于代码:
该代码用于获取元素的 css 属性。
问题:
正如我上面所描述的,问题是由@wazz 报告的,谢谢。
请查看给定链接中的评论部分。
提前致谢。
更新:这是我的完整代码
$(".sample").click(function() {
var html = [],
x = $(this).css([
"margin", "padding", "color", "border"
]);
$.each(x, function(prop, value) {
html.push(prop + ": " + value);
});
$("#result").html(html.join("<br>"));
})
.sample {
margin: 10px;
color: #000;
padding: 5px;
border: 1px solid #4073ff;
}
#test {
background: url(../sample.jpg) 20px 20px no-repeat cover red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
<button class="sample">Click</button>
最佳答案
var elem1 = document.getElementById("elemId");
var style = window.getComputedStyle(elem1, null);
var keys = Object.keys(style); // will give margin,padding,color etc as keys
var marginRight = style.margin-right;
这将为您提供一个带有键作为属性名称的样式对象。在 Firefox 中工作就像一个魅力
关于javascript - 为什么此代码在 Firefox、Safari 和 Edge 上无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44644668/