一个小问题,彩色背景onclick

时间:2018-02-28 16:59:17

标签: javascript

我的目标:每次点击它时更改气球的颜色。 我的问题:控制台日志告诉我第一次我的颜色是空的而不是从css获取数据气球将是蓝色而不是绿色。你知道为什么吗 ?你有什么提示可以解决这个问题吗?

function change() {
  var balloon = document.getElementById("balloon");
  var color = balloon.style.backgroundColor;
  if (color == "red")
    color = "green";
  else
    color = "blue";
  balloon.style.backgroundColor = color;
}
body {
  display: flex;
  justify-content: center;
  padding-top: 50%;
}

#balloon {
  width: 200px;
  height: 200px;
  background-color: red;
  border-radius: 100%;
}
<div id="balloon" onclick="change();"></div>

3 个答案:

答案 0 :(得分:0)

你可以试试这个

var element = document.getElementById('balloon'),
    style = window.getComputedStyle(element),
Color = style.getPropertyValue('backgroundColor');

答案 1 :(得分:0)

您正在使用style属性来检查元素的background-color属性,但您应该使用window.getComputedStyle()方法来检查应用于元素的CSS规则,因此您必须改变你的代码。

change()函数:

function change() {
  var balloon = document.getElementById("balloon");
  var color = window.getComputedStyle(balloon, null).getPropertyValue('background-color');
  if (color == "red")
    color = "green";
  else
    color = "blue";
  balloon.style.backgroundColor = color;
}

style proprety用于应用样式规则,而window.getComputedStyle()方法用于检索样式规则。

答案 2 :(得分:0)

第一次调用事件处理函数时,必须使用window.getComputedStyle()而不是element.style.backgroundColor,因为您在样式表中定义background-color而不是直接在元素上定义var red = 'rgb(255, 0, 0)'; document.getElementById("balloon").addEventListener('click', change); function change() { var color = this.style.backgroundColor || getComputedStyle(this, null).getPropertyValue("background-color"); this.style.backgroundColor = getNextColor(color); } function getNextColor(currentColor) { var color = null; if (currentColor == "red" || currentColor == red) color = "green"; else if (currentColor == "green") color = "blue"; else color = "red" return color; }。下面的代码应该做你想要实现的目标。

Check out this related SO question for more detail on window.getComputedStyle()

body {
  display: flex;
  justify-content: center;
  /*padding-top: 50%;*/
}

#balloon {
  width: 200px;
  height: 200px;
  background-color: red;
  border-radius: 100%;
}
<div id="balloon"></div>
for-each-group