简体   繁体   English

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

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

I wanna to get element background value from javascript file. 我想从javascript文件中获取元素背景值 I has three files - 我有三个文件-

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

html.html 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 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 js.js

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

After running the scrpit,I only get blank alert box. 运行scrpit后,我只得到空白警报框。

How can i get div background value ? 如何获得div背景值

You can replace your alert() with this 您可以用以下内容替换您的alert()

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

or 要么

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

And modify your html a little bit if you using the first one. 并稍微修改一下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