开发者

Javascript show element on click

I'm trying to do this without Jquery. I want to show a div when clicking a trigger. So far I have this to hide the element.

 document.getElementById('element').style.display = 'none';

HTML..

<div class="element">Ahem, boo!!</div>
<a href="#" id="showDiv">Show</a>

How do I create a function to show the开发者_JAVA百科 div when clicking the link? I would like to avoid using functions like onclick="showDiv() in the link itself.


document.getElementById('showDiv').onclick=function(){
  // Remove any element-specific value, falling back to stylesheets
  document.getElementById('element').style.display='';
};


It's possible to attach event handlers completely within JavaScript. Example:

document.getElementById('showDiv').onclick = function() {
    // Do whatever now that the user has clicked the link.
};

To reverse the effect of the first line of code you posted, you could use:

document.getElementById('element').style.display = 'block'; // or
document.getElementById('element').style.display = '';


Add this to the script:

function myFunction() {

            var btn = document.getElementById("myButton");
            //to make it fancier
            if (btn.value == "Click To Open") {
                btn.value = "Click To Close";
                btn.innerHTML = "Click To Close";
            }
            else {
                btn.value = "Click To Open";
                btn.innerHTML = "Click To Open";
            }
            //this is what you're looking for
            var x = document.getElementById("myDIV");
            if (x.style.display === "none") {
                x.style.display = "block";
            } else {
                x.style.display = "none";
            }
        }

and edit the button and div:

<button onclick="myFunction()" id="myButton" value="Click To Open Instructions">Click To Open Instructions</button>

 <div style="display:none;" id="myDIV">
</div>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜