[英]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>
我在这里错过了什么吗?
这是因为您的元素样式不透明。 只有你的元素的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>
元素不以透明的背景颜色开始,因此它总是转到else。 将div更改为
<div id="container" onclick="selected(this)" style='background-color:transparent'>www</div>
会使它工作。 css样式表不会在物理上为DOM元素添加样式。
以上两个答案绝对同意最初的风格没有设定。
只是告诉你下次如何DEBUG它我们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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.