开发者

CSS Display/Hide Methods

I just fixed this issue but I am still puzzled on why I was having trouble. When trying to hide a div I tried to use this code:

<div id = myDiv></div>开发者_StackOverflow社区

function MyFunction(){
    $('#myDiv').css("display", "none");
}

That code would not work when trying to hide the div, but this will

  function MyFunction(){
    $('#myDiv').hide();
}

I wanted to know what the difference was between each of these methods, and why one would work while the other did not.


This is a problem

<div id = myDiv></div>

You have to do like this

<div id="myDiv"></div>

Since both .hide() and .css() will add "display: none" to your element, the above code is the only thing I could think of. Always use "" with attributes.


Copied out exactly how you have it, the code doesn't work, but you might not have meant it all literally. Just in case, it should be something like (notice the script block and the correct spacing and quotation on the div tag):

<div id="myDiv">hello world</div>
<script type="text/javascript">
    function MyFunction(){
        $('#myDiv').css("display", "none");
    }
</script>

So if that wasn't your problem, there must be something else going on on the page somewhere that's breaking your html/css.


Rather than change the css directly, it is better practice to add and remove a class that contains the display declarations you want.

So

$('#myDiv').addClass('hidden');

adds

.hidden {
  display: none;
}

I find this method to be much more reliable and flexible.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜