将样式从内联移动到头部破坏了用于显示borderColor的简单javascript

Moving style from inline to head breaks simple javascript made to show borderColor

本文关键字:显示 用于 坏了 borderColor javascript 简单 头部 样式 移动      更新时间:2023-09-26

开始学习web开发,偶然发现一些简单的东西,我在过去的一个小时里一直在打破我的头。用alert显示div元素的边框颜色是很简单的代码。它的工作原理。但是当我将样式从内联移动到style元素时,它什么也不返回。

工作代码:

function myFunction() {
  alert(document.getElementById("myDiv").style.borderColor);
}
<div id="myDiv" style="border:thick solid green">This is a div.</div>
<br>
<button type="button" onclick="myFunction()">Return border color</button>

非工作代码:

function myFunction() {
  alert(document.getElementById("myDiv").style.borderColor);
}
<style>
  #myDiv {
    border: thick solid green;
  }
</style>
<div id="myDiv">This is a div.</div>
<br>
<button type="button" onclick="myFunction()">Return border color</button>

我唯一改变的是将样式属性从div标签移动到头部。为什么它停止工作,我如何解决它?

style属性为您提供内联样式。要获得computed样式,您可以在基于标准的浏览器上使用getComputedStyle(一个全局函数),或者在旧的IE上使用currentStyle(一个元素属性):

function myFunction() {
  var div = document.getElementById("myDiv");
  var style = window.getComputedStyle ? getComputedStyle(div) : div.currentStyle;
  alert(style.borderColor);
}
<style>
  #myDiv {
    border: thick solid green;
  }
</style>
<div id="myDiv">This is a div.</div>
<br>
<button type="button" onclick="myFunction()">Return border color</button>

使用element.style读取元素的style属性。在第二个示例中,您删除了该属性,这就是它停止工作的原因。

要获得应用于元素的实际样式,您需要使用windows . getcomputedstyle()。使用这个的例子:

var elem = document.getElementById("myDiv");
var styles = window.getComputedStyle(elem);
alert(styles.borderColor);