简体   繁体   中英

JavaScript toggle button only works on second click if display attribute is in header

I came across an interesting quirk, and was wondering if anyone could help me understand it. A simple JavaScript-driven toggle button, as below, works beautifully if the display:none of the toggled element is contained in-line. However, when I move the CSS statement to the <style> tag in the header, or to a separate CSS file, it starts to toggle only on the second click, and from then on, it works fine, on a single-click-per-toggle basis. Here's the JS function:

<script>
    function openSec(ordinal) {
        var tab_name = "sec" + ordinal;
        if (document.getElementById(tab_name).style.display == "none") {
            document.getElementById(tab_name).style.display = "table";
        } else {
            document.getElementById(tab_name).style.display = "none";
        }
    }
</script>

When the CSS statement is in the style tag, it no longer exists as an attribute of the DOM element that is getting clicked. The browser is still applying the style, but the DOM element no longer has that value as a style attribute. So the first click, there is no display:none, so it adds it, then on the second click it replace it with table.

Use your browser's dev tools (or something like Firebug) to examine the initial HTML, then examine it again after the first click and I think you will see a difference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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