简体   繁体   中英

Html/Javascript: Is it possible to set text style.display = “none” by default?

With the way I have my html and javascript set up right now, I have it so when the page loads up and shows up all the text under each button. You can click the button to hide and show the text right below it.

Is it possible to make it so all the text does NOT show up by default?

I was thinking you would have to make e.style.display = "none" by default but I'm not sure how/where to in this particular case.

<script type="text/javascript">

function toggleMe(a)
{
var e=document.getElementById(a);

if(!e)
{

return true;
}

if(e.style.display=="none")
{
e.style.display="block"
}
else
{
e.style.display="none"
}
return true;
}
</script>

<input type="button" onclick="return toggleMe('para1')" value="Toggle"><br>
<p id="para1">
blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah
</p>
<br>
<input type="button" onclick="return toggleMe('para2')" value="Toggle"><br>
<div id="para2">
blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah

</div>
<br>
<input type="button" onclick="return toggleMe('para3')" value="Toggle"><br>
<span id="para3">
blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah

</span>

if you add the following styles to your page, the paragraphs will be hidden by default.

<style>
    #para1, #para2{
        display:none;
    }
</style>

make a class for each element you want hidden by defaut, ie

<p class="hidden">some hidden text</p>
<p class="hidden">more hidden text</p>

<style>
    .hidden
    {
        display:none;
    }
</style>

CSS

First, add this bit of code in order to have a CSS class to make things hidden.

<style>
.hidden { display: none }
</style>

And then, add this class to whichever elements you want hidden by default. For example,

<p id="para1" class="hidden">

Also, here's a short DEMO on how you might shorten all that code using jQuery. There's a toggleClass() function that you can use to easily add / remove (toggle) a class.

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