如何用 jQuery 隐藏 div?

当我想隐藏 HTML <div>时,我使用以下 JavaScript 代码:

var div = document.getElementById('myDiv');
div.style.visibility = "hidden";
div.style.display = "none";

这段代码在 jQuery 中的等价物是什么?

330083 次浏览

Easy:

$('#myDiv').hide();

http://api.jquery.com/hide/

$('#myDiv').hide() will hide the div...

$('#myDiv').hide();

or

$('#myDiv').slideUp();

or

$('#myDiv').fadeOut();
$("#myDiv").hide();

will set the css display to none. if you need to set visibility to hidden as well, could do this via

$("#myDiv").css("visibility", "hidden");

or combine both in a chain

$("#myDiv").hide().css("visibility", "hidden");

or write everything with one css() function

$("#myDiv").css({
display: "none",
visibility: "hidden"
});

$("myDiv").hide(); and $("myDiv").show(); does not work in Internet Explorer that well.

The way I got around this was to get the html content of myDiv using .html().

I then wrote it to a newly created DIV. I then appended the DIV to the body and appended the content of the variable Content to the HiddenField then read that contents from the newly created div when I wanted to show the DIV.

After I used the .remove() method to get rid of the DIV that was temporarily holding my DIVs html.

var Content = $('myDiv').html();
$('myDiv').empty();
var hiddenField = $("<input type='hidden' id='myDiv2'>");
$('body').append(hiddenField);
HiddenField.val(Content);

and then when I wanted to SHOW the content again.

        var Content = $('myDiv');
Content.html($('#myDiv2').val());
$('#myDiv2').remove();

This was more reliable that the .hide() & .show() methods.

If you want the element to keep its space then you need to use,

$('#myDiv').css('visibility','hidden')

If you dont want the element to retain its space, then you can use,

$('#myDiv').css('display','none')

or simply,

$('#myDiv').hide();

$('#myDiv').hide(); hide function is used to edit content and show function is used to show again.

For more please click on this link.