如何使用 JS innerHTML 打印 div 宽度或颜色?

How to print div width or color with JS innerHTML?

我不知道如何使用 getElementById().innerHTML 获取 CSS 参数(正确的术语?)或显示在诸如 p 之类的东西中的值。 抱歉,这是两个问题——当 CSS 值为数字时,我是否需要使用 toString 或类似的东西?

我希望能得到纯 JS 的回答,但如果您认为 jQuery 最好的话,也可以。我在 phone 中的一个名为 HTML + CSS + Javascript 的应用程序上执行此操作——我不知道如何访问 jQuery 库。

HTML:

<body>
     <h1>Practice Page</h1>
    <div id="box">
        <div id="runner"></div>
    </div>
  <p id="color"></p>

  <p id="width"></p>

    <script src="practiceA.js" type="text/javascript"></script>

</body>
</html>

JS:

document.getElementById('color').innerHTML=
document.getElementById('runner').style.backgroundColor;

document.getElementById('width').innerHTML=
document.getElementById('box').style.width;

和CSS:

#runner{
  height:10px;
  width:10px;
  background-color: red; 
}

#box{
   height:100px;
   width:100px;
   border:1px solid black;
}

You can't access CSS properties that were set from a CSS file using element.style 。相反,您需要使用 getComputedStyle,但这可能会影响浏览器兼容性等等,所以我建议使用 jQuery,如下所示。 (如果您选择不使用 jQuery,我链接的答案有一个很好的辅助函数,您可以使用)

jQuery 示例:

$('#color').html($('#runner').css('backgroundColor'));
#runner{
  height:10px;
  width:10px;
  background-color: red; 
}

#box{
   height:100px;
   width:100px;
   border:1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
<h1>Practice Page</h1>
<div id="box">
    <div id="runner"></div>
</div>
<p id="color">x</p>

<script src="practiceA.js" type="text/javascript"></script>

</body>