onclick trigger doesn#39;t work first click(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 触发器在第一次点击时不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:onclick 触发器在第一次点击时不起作用


基础教程推荐
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01