使用 JavaScript,如何根据另一个元素的 CSS 样式更改一个元素的 CSS 样式?

Using JavaScript, how do I change the CSS style of one element based on the CSS style of another element?

我正在尝试根据另一个 div 的 opacity/visibility 来更改一个 div 的高度。看起来这应该很简单,但我尝试的任何东西似乎都不起作用。

我在想它会是这样的:

var red = document.getElementById("red");
var green = document.getElementById("green");

if(red.style.opacity = "0"){
green.style.height = "200px";
}

但这只是改变了不透明度和高度,而没有实际检查不透明度是从什么开始的。

任何关于如何实现我想要的功能的建议都将不胜感激!

您似乎明确设置了不透明度。以下代码应该有效:

if(red.style.opacity == 0){
   green.style.height = "200px";
}

使用 getComputedStyle -

The getComputedStyle() method gets all the actual (computed) CSS property and values of the specified element.

var red = document.getElementById("red");
var rd = window.getComputedStyle(red).getPropertyValue("opacity");
var green = document.getElementById("green");
if (rd == 0) {
  green.style.height = "200px";
}
#red {
  width: 50px;
  height: 50px;
  background: red;
  opacity: 0;
}

#green {
  width: 50px;
  height: 50px;
  background: green;
}
<div id="red">Red</div>
<div id="green">Green</div>