简体   繁体   English

Javascript点击事件需要双击

[英]Javascript click event requires double clicks

I have a simple HTML-CSS-JavaScript page with an event listener on a button to toggle a div. 我有一个简单的HTML-CSS-JavaScript页面,在按钮上可以通过事件监听器切换div。

However, all is working but the animation function takes two clicks first time to work, although i consoled the click event to prove that the button listens to the first click too. 但是,所有功能都可以正常运行,但是动画功能第一次需要两次单击才能工作,尽管我已控制click事件以证明按钮也监听了第一次单击。

i tried to wrap into window.onload but same thing. 我试图包装到window.onload但同样的事情。

note: i want to use pure javascript only. 注意:我只想使用纯JavaScript。 thank you 谢谢

this pic shows the first click (it says "clicked" in the console): 此图片显示了第一次点击(在控制台中显示为“已点击”):

首次点击后

this pic shows the second click (animation took place): 此图片显示了第二次点击(动画发生):

第二次点击后

Here is my code: 这是我的代码:

            var showDivButton = document.getElementById('showDivButton');
            var info =  document.getElementById('info');

            showDivButton.addEventListener('click', animation) ;

            // animation func
            function animation () { 
                console.log('Clicked!');
                if (info.style.display === 'none'){
                    info.style.display =  'inline-block';
                    showDivButton.style.background = 'green';
                } else {
                     info.style.display =  'none';
                     showDivButton.style.background = 'gray';
                }

            }

Look at My Plunker Here please. 请在这里查看我的柱塞 Thank you in advance. 先感谢您。

Try to revise your function block as follow: 尝试如下修改功能块:

function animation () { 
    console.log('Clicked!');
    if (info.style.display == '' || info.style.display == 'none'){
        info.style.display =  'inline-block';
        showDivButton.style.background = 'green';
    } else {
         info.style.display =  'none';
         showDivButton.style.background = 'gray';
    }

}

info.style.display is '' on initial info.style.display在初始为''

Because info.style.display refers to the style attribute of your div, not the computed Style, so on the first click, this is not set. 因为info.style.display是指div的style 属性 ,而不是计算的Style,所以在第一次单击时未设置。

You may want to look at getComputedStyle , but i would advise switching class instead of directly modifying style. 您可能想看看getComputedStyle ,但我建议您切换类,而不是直接修改样式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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