Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

css - Javascript: Hiding and Showing div tag with a toggle button

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, press again to show, press again to hide etc...

I want the hide/show rules to be done in CSS and the interaction in pure javascript (no jquery please). Well this is what I need to do, but I'm not quite sure how to execute the javascript code.

html:

<p class="button">Show/hide<p>

<div> I want to hide this by pressing the button above</div>

css:

#showhide {
     display: none;
}

.button {
    display: block;
    height: 30px;
    width: 100px;
    background: green;
    text-align: center;
    padding-top: 10px;
    padding-left: 0px;
    font: 15px arial bold;
    border: 1px solid black;
    text-decoration: none;
    list-style:none;
    margin: 10px 0px 10px 0px;
}

http://jsfiddle.net/fyUJc/14/

Also, if you think this question doesn't belong here or is stupid, please try to refrain from being rude, I'm just trying to learn here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can make use an onclick method. Have your HTML as:

<p class="button" onclick="toggle_visibility('hideMe')">Show/hide</p>
<div id="hideMe">I want to hide this by pressing the button above</div>

And have the following JavaScript:

function toggle_visibility(id) 
{
    var e = document.getElementById(id);
    if (e.style.display == 'block' || e.style.display=='')
    {
        e.style.display = 'none';
    }
    else 
    {
        e.style.display = 'block';
    }
}

DEMO


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...