我试图通过querySelector
获取CSS类的特定值,但仍无法找到解决方案:
我想要得到的是" 40px"值:
function onS(obj) {
var logo = document.querySelector('.logo');
var value = logo.style.marginLeft;
alert(value);
}

.logo { display: block; position: relative; margin-left: 40px; }

<div class="logo" onmouseover="onS(this)">Test!</div>
&#13;
有什么办法吗?
答案 0 :(得分:3)
logo.style
只是查看内联style
属性,它没有获得计算出的样式。
要从<style>
标记或外部样式表中获取CSS值,请使用window.getComputedStyle()
function onS(obj) {
var logo = document.querySelector('.logo');
var value = window.getComputedStyle(logo).marginLeft;
alert(value);
}
&#13;
.logo { display: block; position: relative; margin-left: 40px; }
&#13;
<div class="logo" onmouseover="onS(this)">Test!</div>
&#13;
答案 1 :(得分:1)
我使用jQuery来获取值......
function onS(obj) {
var logo = $('.logo');
var value = logo.css('marginLeft');
alert(value);
}
.logo { display: block; position: relative; margin-left: 40px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="logo" onmouseover="onS(this)">Test!</div>