Js style.display='' invalid solution

  • 2020-03-30 04:12:49
  • OfStack

This example illustrates an invalid solution to style.display="" in js. Share with you for your reference. Specific solutions are as follows:

I. problem description:

In js we sometimes want to dynamically control a div to show or hide or more operations, but if we style.display="" it may not work.

Take a look at the following code:

<style>
 #name
 {
     display:none;
 }
</style>
</head>
<body>
<div id="name" >
My name is smile.
</div>
</body>
</html>
<script>
window.onload=function(){
document.getElementById('name').style.display="";
 alert("test");
}
</script>

CSS defines div with id name to be hidden, and we use js to control the id to be displayed after the page is loaded. Is there anything wrong with this?
There is nothing wrong? But why is the interface still blank?

Ii. Solutions:

Remember the other one is xxx.style.display="block" so let's try that,
Alas shout, unexpectedly showed!!

So let's look at the difference between style.display="" and style.display="block".
In fact, the big difference between the two is that blocks are shown as blocks, so they break lines, so that's all there is to it, why does one show and one not in this case ? Obsession.
Ok, let's let this problem go, and let's see how we can solve it in this problem. Besides solving it with style.display="block", there is another way:

<div id="name" style="display:none" >
My name is smile.
</div>
<script>
     document.getElementById('name').style.display="";
</script>

I'm just going to put the style of id name in the label with style, so it doesn't matter if we're using display="" or display="block", it's going to work!


Related articles: