Javascript style.color不起作用

时间:2017-05-18 03:07:25

标签: javascript html css



function myFunction() {
    alert(document.getElementById("myP").style.color);
}

#myP {
  color: pink;
}

<!DOCTYPE html>
<html>
<body>

<p id="myP">This is an example paragraph.</p>

<button type="button" onclick="myFunction()">Return text color of p</button>




</body>
</html>
&#13;
&#13;
&#13;

如果我这样做

<p id="myP" style="color: pink;">This is an example paragraph.</p> 

正确返回颜色值。

如果在css中设置了值,我该如何获取颜色值?

我需要Javascript而不是JQuery。

感谢。

1 个答案:

答案 0 :(得分:3)

试用此代码

var element = document.getElementById('myP'),
    style = window.getComputedStyle(element),
    color = style.getPropertyValue('color');
alert(color);

DEMO