通过querySelector从CSS获取价值

时间:2016-06-08 14:50:51

标签: javascript jquery html css

我试图通过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;
&#13;
&#13;

有什么办法吗?

2 个答案:

答案 0 :(得分:3)

logo.style只是查看内联style属性,它没有获得计算出的样式。

要从<style>标记或外部样式表中获取CSS值,请使用window.getComputedStyle()

&#13;
&#13;
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;
&#13;
&#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>