本文介绍了onclick 触发器在第一次点击时不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

function selected(elmnt) {if (elmnt.style.backgroundColor == "透明")elmnt.style.backgroundColor = "#990000"别的elmnt.style.backgroundColor = "透明"}
#container {背景颜色:透明;高度:100px;宽度:100px;}
<div id="container" onclick="selected(this)">点我</div>

我错过了什么吗?

解决方案

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

function selected(elmnt) {if (elmnt.style.backgroundColor == "透明")elmnt.style.backgroundColor = "#990000"别的elmnt.style.backgroundColor = "透明"}
#container {背景颜色:透明;高度:100px;宽度:100px;}
<div id="container" onclick="selected(this)" style="background-color: transparent;">click我</div>

还有自然的方式:

function selected(elmnt) {if (elmnt.style.backgroundColor == "")elmnt.style.backgroundColor = "#990000"别的elmnt.style.backgroundColor = ""}
#container {背景颜色:透明;高度:100px;宽度:100px;}
<div id="container" onclick="selected(this)">点我</div>

I'm confused why the onclick function doesn't register the first time it is clicked. Each div with the onclick trigger has to be clicked twice the first time.

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>

Am I missing something here?

解决方案

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>

这篇关于onclick 触发器在第一次点击时不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-02 12:08