简体   繁体   中英

Hide/Show css div with javascript - does not show again after hide -

The div 'container' is hidden once I do a mouseover. When I do again a mouseover on the empty space where the div is supposed to be nothing happens means its not getting visible.

What do I wrong?

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

   <script type="text/javascript">
       function ShowUserInterface(containerToSwitch) {
           debugger;
           var element = document.getElementById(containerToSwitch);

           if (element.getAttribute("visibility") == "hidden")
               element.setAttribute("style", "visibility: visible");
           else
               element.setAttribute("style", "visibility: hidden");  


       }
</script> 
<div  style="visibility:visible;width:200px;height:200px;background-color:Aqua" onmouseover="ShowUserInterface(this.id)" id="container" >
    <uc1:WebUserControl ID="WebUserControl1" runat="server" />
</div>
</asp:Content>

Hidden element can't fire events, so in your case I see only one possible solution: use style.opacity = 0 and style.opacity = 1 instead of style.visibility = 'hidden' and style.visibility = 'visible' . But this won't work in old browsers.

Also if you want to get some style attribute use element.style.visibility , not element.getAttribute('visibility') :

if (element.style.visibility == "hidden")
    element.style.visibility = "visible";
else
    element.style.visibility = "hidden";

Or better use some js framework (jQuery, prototype.js, mootools), especially if your project requires much of JavaScript.

try this

" if (element.style.visibility == "hidden") element.style.visibility = "visible"; else element.style.visibility = "hidden";
"

This function clears all previous style info so not a best practice do toogle something.

Instead use

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

Your checking for the visibility attribute on the element, but it's actually on the style object -- but you might be surprised with results even when you do element.style.visibility as this might not always give you the right result (in your case it will, because your setting inline styles which is bad practice anyway)

Let's assume you set your CSS style on the element like so:

#user { visibility: hidden; }

Then you checked for it:

alert(document.getElementById('user').style.visibility);

It'll contain an empty string "" -- instead you should ideally use getComputedStyle to actually get what styles are IN USE.

我当时专注于div ...现在进行显示:无/用表阻止并且它起作用。

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