onclick触发器无法首次单击

thi*_*ard 2 javascript onclick

我很困惑为什么onclick函数在第一次点击时没有注册.每次使用onclick触发器的div都必须在第一次点击两次.

function selected(elmnt) {
  if (elmnt.style.backgroundColor == "transparent")
    elmnt.style.backgroundColor = "#990000"
  else
    elmnt.style.backgroundColor = "transparent"
}
Run Code Online (Sandbox Code Playgroud)
#container {
  background-color: transparent;
  height: 100px;
  width: 100px;
}
Run Code Online (Sandbox Code Playgroud)
<div id="container" onclick="selected(this)">click me</div>
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么吗?

Pra*_*man 7

这是因为您的元素样式不透明.只有你的元素computedStyle是.试试这个:

function selected(elmnt) {
  if (elmnt.style.backgroundColor == "transparent")
    elmnt.style.backgroundColor = "#990000"
  else
    elmnt.style.backgroundColor = "transparent"
}
Run Code Online (Sandbox Code Playgroud)
#container {
  background-color: transparent;
  height: 100px;
  width: 100px;
}
Run Code Online (Sandbox Code Playgroud)
<div id="container" onclick="selected(this)" style="background-color: transparent;">click me</div>
Run Code Online (Sandbox Code Playgroud)

还有一种自然的方式:

function selected(elmnt) {
  if (elmnt.style.backgroundColor == "")
    elmnt.style.backgroundColor = "#990000"
  else
    elmnt.style.backgroundColor = ""
}
Run Code Online (Sandbox Code Playgroud)
#container {
  background-color: transparent;
  height: 100px;
  width: 100px;
}
Run Code Online (Sandbox Code Playgroud)
<div id="container" onclick="selected(this)">click me</div>
Run Code Online (Sandbox Code Playgroud)