繁体   English   中英

我如何从外部JS文件获取外部CSS值?

[英]How i get external CSS value From external JS file?

我想从javascript文件中获取元素背景值 我有三个文件-

  1. html.html
  2. css.css
  3. js.js

html.html

<!DOCTYPE html>
<html>
<head>
    <title> I'm Button! </title>
    <link rel="stylesheet" type="text/css" href="css.css"/>
    <script type="text/javascript" src="js.js"></script>
</head>
<body>
    <div class="myBlock" onclick="heyJS()"></div>

</body>
</html>

css.css

.myBlock {
  width: 300px; max-width: 100%;
  height: 100px; max-height: 100%;
  margin: 0 auto; margin-top: 100px; 
  font-size: 50px; font-weight: lighter; font-style: normal; text-align: center;
  line-height: 100px; position: relative;
  background-color: #83DF31;
}

js.js

function heyJS() {
    alert(document.getElementsByClassName('myBlock')[0].style.backgroundColor);
}

运行scrpit后,我只得到空白警报框。

如何获得div背景值

您可以用以下内容替换您的alert()

alert(window.getComputedStyle(document.getElementById('myBlock')).backgroundColor);

要么

alert(window.getComputedStyle(document.getElementsByClassName('myBlock')[0]).backgroundColor);

并稍微修改一下html(如果使用第一个)。

<div id="myBlock" class="myBlock" onclick="heyJS()"></div>

请尝试以下操作:

window.getComputedStyle(document.querySelector(".myblock")).getPropertyValue("background-color");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM