onclick 触发器不起作用首先单击

onclick trigger doesn't work first click

我很困惑为什么第一次点击时 onclick 函数没有注册。每个带有 onclick 触发器的 div 必须在第一次单击两次。

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

我是不是漏掉了什么?

该元素不是以透明背景颜色开始的,因此它总是转到其他位置。将 div 更改为

<div id="container" onclick="selected(this)" style='background-color:transparent'>www</div>

会成功的。 css 样式 sheet 不会在物理上将样式附加到 DOM 元素。

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

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

还有一种自然的方式:

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

以上两个答案完全同意最初未设置样式。

只是告诉你下次如何调试它 我们 console.log() 点击 F12 进入开发者工具,然后点击控制台标签

当简单 IF

时,我是短 IF 的粉丝
 <script>
    function selected(elmnt) {
        console.log(elmnt.style.backgroundColor)
        var bG= elmnt.style.backgroundColor
        elmnt.style.backgroundColor = ( bG == '' || bG == "transparent") ? "#990000" : "transparent";
    }      
</script>