[removed] Hiding and Showing div tag with a toggle button

前端 未结 4 2066
鱼传尺愫
鱼传尺愫 2020-12-11 23:46

I\'ll get right to it:

What I need to do is hide a particular div with the press of a button, and it\'s supposed to be a toggle, so basically: Press once to hide, pr

4条回答
  •  庸人自扰
    2020-12-12 00:13

    You can add attach an event listener to the P tag and have that call a Toggle() function to swap the display value as shown below.

    Example here - JSFiddle

    function Toggle() {
        var div = document.getElementsByTagName('div')[0];
    
        if (div.style.display == 'none') {
            div.style.display = 'block';
        } else {
            div.style.display = 'none';
        }
    }
    
    (function () {
    
        var button = document.querySelectorAll(".button");
    
        for (var i = 0; i < button.length; i++) {
            if (button[i].addEventListener) {
                button[i].addEventListener("click", function () {
                    Toggle();
                });
            } else {
                button[i].attachEvent("click", function () {
                    Toggle();
                });
            }
        }
    })();
    

    Though you would be better adding IDs to your elements to make them easier to reference.

提交回复
热议问题