简体   繁体   English

onclick触发器无法首次单击

[英]onclick trigger doesn't work first click

I'm confused why the onclick function doesn't register the first time it is clicked. 我很困惑为什么onclick函数在第一次点击时没有注册。 Each div with the onclick trigger has to be clicked twice the first time. 每次使用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> 

Am I missing something here? 我在这里错过了什么吗?

It is because your element style is not transparent. 这是因为您的元素样式不透明。 Only your element's computedStyle is. 只有你的元素的computedStyle是。 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. 元素不以透明的背景颜色开始,因此它总是转到else。 Changing the div to 将div更改为

<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. css样式表不会在物理上为DOM元素添加样式。

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 只是告诉你下次如何DEBUG它我们console.log()单击F12开发人员工具然后单击控制台选项卡

I am fan of short IFs when simple IF 当简单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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM