onclick触发器无法首次单击 [英] onclick trigger doesn't work first click

查看:68
本文介绍了onclick触发器无法首次单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑为什么onclick函数在第一次点击时没有注册。带有onclick触发器的每个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?

推荐答案

这是因为你的元素风格不透明。只有元素的 computedStyle 是。试试这个:

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>

还有一种自然的方式:

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触发器无法首次单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆