onclick trigger doesn't work first click

吃可爱长大的小学妹 提交于 2019-12-02 02:43:00

It is because your element style is not transparent. Only your element's computedStyle is. Try this:

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>

There's also the natural way:

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>

The element doesn't start with a background-color of transparent so it always goes to the else. Changing the div to

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

will make it work. A css style sheet doesnt' append style to the DOM elements physically.

Both answers above absolutely agree initially style is not set.

Just to tell you for next time how to DEBUG it us console.log() click F12 for developer tools then console tab

I am fan of short IFs when simple IF

 <script>
    function selected(elmnt) {
        console.log(elmnt.style.backgroundColor)
        var bG= elmnt.style.backgroundColor
        elmnt.style.backgroundColor = ( bG == '' || bG == "transparent") ? "#990000" : "transparent";
    }      
</script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!