It is possible to toggle the visibility of an element, using the functions .hide()
, .show()
or .toggle()
.
可以使用.hide()、.show()或.toggle()函数来切换元素的可见性。
How would you test if an element is visible or hidden?
如何测试一个元素是可见的还是隐藏的?
53 个解决方案
#1
8212
Since the question refers to a single element, this code might be more suitable:
由于问题涉及单个元素,因此本代码可能更适合:
// Checks css for display:[none|block], ignores visibility:[true|false]
$(element).is(":visible");
Same as twernt's suggestion, but applied to a single element; and it matches the algorithm recommended in the jQuery FAQ
与twernt的建议相同,但适用于单个元素;它匹配jQuery FAQ中推荐的算法
#2
#3
774
if ( $(element).css('display') == 'none' ){
// element is hidden
}
Functions don't work with the visibility attribute.
函数不使用可见性属性。
#4
444
None of these answers address what I understand to be the question, which is what I was searching for, "How do I handle items that have visibility: hidden
?". Neither :visible
nor :hidden
will handle this, as they are both looking for display per the documentation. As far as I could determine, there is no selector to handle CSS visibility. Here is how I resolved it (standard jQuery selectors, there may be a more condensed syntax):
这些答案都没有回答我所理解的问题,也就是我正在寻找的问题:“我如何处理具有可见性的项目:隐藏?”none:visible和:hidden将处理这个,因为它们都在根据文档查找显示。就我所知,没有选择器来处理CSS可见性。下面是我解析它的方法(标准jQuery选择器,可能有更简洁的语法):
$(".item").each(function() {
if ($(this).css("visibility") == "hidden") {
// handle non visible state
} else {
// handle visible state
}
});
#5
317
From How do I determine the state of a toggled element?
如何确定要切换的元素的状态?
You can determine whether an element is collapsed or not by using the :visible
and :hidden
selectors.
可以使用:visible和:hidden选择器来确定元素是否已折叠。
var isVisible = $('#myDiv').is(':visible');
var isHidden = $('#myDiv').is(':hidden');
If you're simply acting on an element based on its visibility, you can just include :visible
or :hidden
in the selector expression. For example:
如果您只是根据元素的可见性对其进行操作,那么可以在选择器表达式中包含:visible或:hidden。例如:
$('#myDiv:visible').animate({left: '+=200px'}, 'slow');
#6
232
Often when checking if something is visible or not, you are going to go right ahead immediately and do something else with it. jQuery chaining makes this easy.
通常,当检查某物是否可见时,您将立即进行操作,并对其进行其他操作。jQuery链接让这变得简单。
So if you have a selector and you want to perform some action on it only if is visible or hidden, you can use filter(":visible")
or filter(":hidden")
followed by chaining it with the action you want to take.
因此,如果您有一个选择器,并且您想要对它执行一些操作,只有在它是可见的或隐藏的时候,您可以使用filter(“:visible”)或filter(“:hidden”),然后用您想要执行的操作对它进行链接。
So instead of an if
statement, like this:
所以不是if语句,像这样
if ($('#btnUpdate').is(":visible"))
{
$('#btnUpdate').animate({ width: "toggle" }); // Hide button
}
Or more efficient, but even uglier:
或者更有效,但更丑:
var button = $('#btnUpdate');
if (button.is(":visible"))
{
button.animate({ width: "toggle" }); // Hide button
}
You can do it all in one line:
你可以用一句话来做:
$('#btnUpdate').filter(":visible").animate({ width: "toggle" });
#7
184
The :visible
selector according to the jQuery documentation:
根据jQuery文档可见选择器:
- They have a CSS
display
value ofnone
.- 它们的CSS显示值为none。
- They are form elements with
type="hidden"
.- 它们是带有type="hidden"的表单元素。
- Their width and height are explicitly set to 0.
- 它们的宽度和高度被显式设置为0。
- An ancestor element is hidden, so the element is not shown on the page.
- 一个祖先元素被隐藏,所以元素不会显示在页面上。
Elements with
visibility: hidden
oropacity: 0
are considered to be visible, since they still consume space in the layout.具有可见性的元素:隐藏或不透明:0被认为是可见的,因为它们仍然在布局中占用空间。
This is useful in some cases and useless in others, because if you want to check if the element is visible (display != none
), ignoring the parents visibility, you will find that doing .css("display") == 'none'
is not only faster, but will also return the visibility check correctly.
这在某些情况下是有用的,在其他情况下是无用的,因为如果您想检查元素是否可见(display != none),忽略父元素的可见性,您将发现执行.css(“display”)= 'none'不仅速度更快,而且还会正确地返回可见性检查。
If you want to check visibility instead of display, you should use: .css("visibility") == "hidden"
.
如果要检查可见性而不是显示,应该使用:.css(“visibility”)==“hidden”。
Also take into consideration the additional jQuery notes:
还要考虑到jQuery新增的注释:
Because
:visible
is a jQuery extension and not part of the CSS specification, queries using:visible
cannot take advantage of the performance boost provided by the native DOMquerySelectorAll()
method. To achieve the best performance when using:visible
to select elements, first select the elements using a pure CSS selector, then use.filter(":visible")
.因为:visible是jQuery扩展,而不是CSS规范的一部分,使用:visible的查询无法利用本机DOM querySelectorAll()方法提供的性能提升。要在使用:visible时实现最佳性能以选择元素,首先使用纯CSS选择器选择元素,然后使用.filter(“:visible”)。
Also, if you are concerned about performance, you should check Now you see me… show/hide performance (2010-05-04). And use other methods to show and hide elements.
另外,如果你担心性能,你应该检查你看到我了…显示/隐藏性能(2010-05-04)。并使用其他方法来显示和隐藏元素。
#8
165
This works for me, and I am using show()
and hide()
to make my div hidden/visible:
这对我来说是可行的,我使用show()和hide()使我的div隐藏/可见:
if( $(this).css('display') == 'none' ){
/* your code goes here */
} else {
/* alternate logic */
}
#9
163
How element visibility and jQuery works;
元素可见性和jQuery如何工作;
An element could be hidden with display:none
, visibility:hidden
or opacity:0
. The difference between those methods:
元素可以用display:none、visibility:hidden或透明度:0隐藏。这些方法的区别是:
-
display:none
hides the element, and it does not take up any space; - 显示:没有隐藏元素,它不占用任何空间;
-
visibility:hidden
hides the element, but it still takes up space in the layout; - 可见性:隐藏隐藏元素,但仍然占用布局空间;
-
opacity:0
hides the element as "visibility:hidden", and it still takes up space in the layout; the only difference is that opacity lets one to make an element partly transparent;不透明度:0将元素隐藏为“可见性:隐藏”,仍然占据布局空间;唯一的区别是不透明可以让一个元素部分透明;
if ($('.target').is(':hidden')) { $('.target').show(); } else { $('.target').hide(); } if ($('.target').is(':visible')) { $('.target').hide(); } else { $('.target').show(); } if ($('.target-visibility').css('visibility') == 'hidden') { $('.target-visibility').css({ visibility: "visible", display: "" }); } else { $('.target-visibility').css({ visibility: "hidden", display: "" }); } if ($('.target-visibility').css('opacity') == "0") { $('.target-visibility').css({ opacity: "1", display: "" }); } else { $('.target-visibility').css({ opacity: "0", display: "" }); }
Useful jQuery toggle methods:
有用的jQuery切换方法:
$('.click').click(function() { $('.target').toggle(); }); $('.click').click(function() { $('.target').slideToggle(); }); $('.click').click(function() { $('.target').fadeToggle(); });
#10
131
I would use CSS class .hide { display: none!important; }
.
我将使用CSS类。hide {display: none!important;}。
For hiding/showing, I call .addClass("hide")/.removeClass("hide")
. For checking visibility, I use .hasClass("hide")
.
为了隐藏/显示,我调用。addclass(“隐藏”)/. removeclass(“隐藏”)。为了检查可见性,我使用. hasclass(“隐藏”)。
It's a simple and clear way to check/hide/show elements, if you don't plan to use .toggle()
or .animate()
methods.
如果不打算使用.toggle()或.animate()方法,这是一种检查/隐藏/显示元素的简单而清晰的方法。
#11
125
You can also do this using plain JavaScript:
你也可以使用普通的JavaScript:
function isRendered(domObj) {
if ((domObj.nodeType != 1) || (domObj == document.body)) {
return true;
}
if (domObj.currentStyle && domObj.currentStyle["display"] != "none" && domObj.currentStyle["visibility"] != "hidden") {
return isRendered(domObj.parentNode);
} else if (window.getComputedStyle) {
var cs = document.defaultView.getComputedStyle(domObj, null);
if (cs.getPropertyValue("display") != "none" && cs.getPropertyValue("visibility") != "hidden") {
return isRendered(domObj.parentNode);
}
}
return false;
}
Notes:
注:
-
Works everywhere
工作无处不在
-
Works for nested elements
适合嵌套的元素
-
Works for CSS and inline styles
适用于CSS和内联样式。
-
Doesn't require a framework
不需要一个框架
#12
104
One can simply use the hidden
or visible
attribute, like:
可以简单地使用隐藏或可见属性,如:
$('element:hidden')
$('element:visible')
Or you can simplify the same with is as follows.
或者你也可以化简如下。
$(element).is(":visible")
#13
97
Another answer you should put into consideration is if you are hiding an element, you should use jQuery, but instead of actually hiding it, you remove the whole element, but you copy its HTML content and the tag itself into a jQuery variable, and then all you need to do is test if there is such a tag on the screen, using the normal if (!$('#thetagname').length)
.
你应该考虑另一个答案是如果你隐藏一个元素,您应该使用jQuery,但实际上隐藏它,而是你删除整个元素,但你复制它的HTML内容和标签本身变成一个jQuery变量,然后你需要做的就是测试如果有这样一个标签在屏幕上,使用正常,如果(! $(' # thetagname '). length)。
#14
90
ebdiv
should be set to style="display:none;"
. It is works for show and hide:
ebdiv应该设置为style="display:none;"。它是用来展示和隐藏的:
$(document).ready(function(){
$("#eb").click(function(){
$("#ebdiv").toggle();
});
});
#15
90
$('#clickme').click(function() {
$('#book').toggle('slow', function() {
// Animation complete.
alert($('#book').is(":visible")); //<--- TRUE if Visible False if Hidden
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clickme">
Click here
</div>
<img id="book" src="http://www.chromefusion.com/wp-content/uploads/2012/06/chrome-logo.jpg" alt="" />
Source:
来源:
Blogger n Play - jQuery工具和小部件:如何使用jQuery查看元素是否隐藏或可见
jsFiddle:
jsFiddle:
JSFiddle - ipsjolly - k4WWj
#16
78
When testing an element against :hidden
selector in jQuery it should be considered that an absolute positioned element may be recognized as hidden although their child elements are visible.
在jQuery中测试一个元素时,应该考虑到一个绝对定位元素可以被识别为隐藏的,尽管它们的子元素是可见的。
This seems somewhat counter-intuitive in the first place – though having a closer look at the jQuery documentation gives the relevant information:
乍一看,这似乎有点反直觉——不过仔细看看jQuery文档就会得到相关信息:
Elements can be considered hidden for several reasons: [...] Their width and height are explicitly set to 0. [...]
可以认为元素隐藏有以下几个原因:它们的宽度和高度被显式地设置为0。[…]
So this actually makes sense in regards to the box-model and the computed style for the element. Even if width and height are not set explicitly to 0 they may be set implicitly.
这对于方框模型和元素的计算风格来说是有意义的。即使宽度和高度没有显式地设置为0,也可以隐式地设置它们。
Have a look at the following example:
请看下面的例子:
console.log($('.foo').is(':hidden')); // true
console.log($('.bar').is(':hidden')); // false
.foo {
position: absolute;
left: 10px;
top: 10px;
background: #ff0000;
}
.bar {
position: absolute;
left: 10px;
top: 10px;
width: 20px;
height: 20px;
background: #0000ff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">
<div class="bar"></div>
</div>
UPDATE FOR JQUERY 3.x:
更新JQUERY 3. x:
With jQuery 3 the described behavior will change! Elements will be considered visible if they have any layout boxes, including those of zero width and/or height.
使用jQuery 3,所描述的行为将会改变!如果元素有任何布局框(包括零宽度和/或高度),则将被认为是可见的。
JSFiddle with jQuery 3.0.0-alpha1:
与jQuery 3.0.0-alpha1 JSFiddle:
http://jsfiddle.net/pM2q3/7/
The same JS will then have this output:
同样的JS将会有这样的输出:
console.log($('.foo').is(':hidden')); // false
console.log($('.bar').is(':hidden')); // false
#17
75
This may work:
这可能工作:
expect($("#message_div").css("display")).toBe("none");
#18
55
To check if it is not visible I use !
:
检查它是否不可见,我使用!
if ( !$('#book').is(':visible')) {
alert('#book is not visible')
}
Or the following is also the sam, saving the jQuery selector in a variable to have better performance when you need it multiple times:
或者下面是sam,在需要多次使用时,将jQuery选择器保存在一个变量中以获得更好的性能:
var $book = $('#book')
if(!$book.is(':visible')) {
alert('#book is not visible')
}
#19
55
Example:
例子:
$(document).ready(function() {
if ($("#checkme:hidden").length) {
console.log('Hidden');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="checkme" class="product" style="display:none">
<span class="itemlist"><!-- Shows Results for Fish --></span> Category:Fish
<br>Product: Salmon Atlantic
<br>Specie: Salmo salar
<br>Form: Steaks
</div>
#20
53
Use class toggling, not style editing . . .
Using classes designated for "hiding" elements is easy and also one of the most efficient methods. Toggling a class 'hidden' with a Display
style of 'none' will perform faster than editing that style directly. I explained some of this pretty thoroughly in Stack Overflow question Turning two elements visible/hidden in the same div.
使用为“隐藏”元素指定的类很容易,也是最有效的方法之一。使用'none'显示样式切换类'hidden'将比直接编辑该样式执行得更快。我在Stack Overflow中详细介绍了其中的一些问题,将两个元素隐藏在同一个div中。
JavaScript Best Practices and Optimization
Here is a truly enlightening video of a Google Tech Talk by Google front-end engineer Nicholas Zakas:
下面是谷歌前端工程师尼古拉斯·扎卡斯主持的谷歌技术讲座的一个非常有启发性的视频:
- Speed Up Your Javascript (YouTube)
- 加快你的Javascript (YouTube)
#21
52
Example of using the visible check for adblocker is activated:
使用可见检查adblocker的例子被激活:
$(document).ready(function(){
if(!$("#ablockercheck").is(":visible"))
$("#ablockermsg").text("Please disable adblocker.").show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ad-placement" id="ablockercheck"></div>
<div id="ablockermsg" style="display: none"></div>
"ablockercheck" is a ID which adblocker blocks. So checking it if it is visible you are able to detect if adblocker is turned On.
“ablockercheck”是adblocker阻塞的ID。所以检查它是否可见你可以检测adblocker是否被打开。
#22
49
After all, none of examples suits me, so I wrote my own.
毕竟,没有一个例子适合我,所以我自己写了。
Tests (no support of Internet Explorer filter:alpha
):
测试(不支持ie滤镜:alpha):
a) Check if the document is not hidden
a)检查文件是否未隐藏
b) Check if an element has zero width / height / opacity or display:none
/ visibility:hidden
in inline styles
b)检查一个元素是否有零宽度/高度/不透明度或显示:无/可见性:隐藏在内联样式中
c) Check if the center (also because it is faster than testing every pixel / corner) of element is not hidden by other element (and all ancestors, example: overflow:hidden
/ scroll / one element over enother) or screen edges
c)检查元素的中心(也因为它比测试每个像素/角都快)是否没有被其他元素(以及所有祖先元素,例如:overflow:hidden / scroll / one element over other)或屏幕边缘隐藏
d) Check if an element has zero width / height / opacity or display:none
/ visibility:hidden in computed styles (among all ancestors)
d)检查元素是否为零宽度/高度/不透明度或显示:无/可见性:隐藏在计算样式中(在所有祖先中)
Tested on
测试
Android 4.4 (Native browser/Chrome/Firefox), Firefox (Windows/Mac), Chrome (Windows/Mac), Opera (Windows Presto/Mac Webkit), Internet Explorer (Internet Explorer 5-11 document modes + Internet Explorer 8 on a virtual machine), Safari (Windows/Mac/iOS)
Android 4.4(本机浏览器/Chrome/Firefox)、Firefox (Windows/Mac)、Chrome (Windows/Mac)、Opera (Windows Presto/Mac Webkit)、Internet Explorer (Internet Explorer 5-11文档模式+ Internet Explorer 8虚拟机)、Safari (Windows/Mac/iOS)
var is_visible = (function () {
var x = window.pageXOffset ? window.pageXOffset + window.innerWidth - 1 : 0,
y = window.pageYOffset ? window.pageYOffset + window.innerHeight - 1 : 0,
relative = !!((!x && !y) || !document.elementFromPoint(x, y));
function inside(child, parent) {
while(child){
if (child === parent) return true;
child = child.parentNode;
}
return false;
};
return function (elem) {
if (
document.hidden ||
elem.offsetWidth==0 ||
elem.offsetHeight==0 ||
elem.style.visibility=='hidden' ||
elem.style.display=='none' ||
elem.style.opacity===0
) return false;
var rect = elem.getBoundingClientRect();
if (relative) {
if (!inside(document.elementFromPoint(rect.left + elem.offsetWidth/2, rect.top + elem.offsetHeight/2),elem)) return false;
} else if (
!inside(document.elementFromPoint(rect.left + elem.offsetWidth/2 + window.pageXOffset, rect.top + elem.offsetHeight/2 + window.pageYOffset), elem) ||
(
rect.top + elem.offsetHeight/2 < 0 ||
rect.left + elem.offsetWidth/2 < 0 ||
rect.bottom - elem.offsetHeight/2 > (window.innerHeight || document.documentElement.clientHeight) ||
rect.right - elem.offsetWidth/2 > (window.innerWidth || document.documentElement.clientWidth)
)
) return false;
if (window.getComputedStyle || elem.currentStyle) {
var el = elem,
comp = null;
while (el) {
if (el === document) {break;} else if(!el.parentNode) return false;
comp = window.getComputedStyle ? window.getComputedStyle(el, null) : el.currentStyle;
if (comp && (comp.visibility=='hidden' || comp.display == 'none' || (typeof comp.opacity !=='undefined' && comp.opacity != 1))) return false;
el = el.parentNode;
}
}
return true;
}
})();
How to use:
如何使用:
is_visible(elem) // boolean
#23
46
You need to check both... Display as well as visibility:
你需要同时检查两个……显示和可见性:
if ($(this).css("display") == "none" || $(this).css("visibility") == "hidden") {
// The element is not visible
} else {
// The element is visible
}
If we check for $(this).is(":visible")
, jQuery checks for both the things automatically.
如果我们检查$(this).is(":visible"), jQuery会自动地检查这两项。
#24
34
Maybe you can do something like this
也许你可以做这样的事情。
$(document).ready(function() {
var visible = $('#tElement').is(':visible');
if(visible) {
alert("visible");
// Code
}
else
{
alert("hidden");
}
});
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<input type="text" id="tElement" style="display:block;">Firstname</input>
#25
29
Because Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout
(as described for jQuery :visible Selector) - we can check if element is really visible in this way:
因为具有可见性:隐藏或不透明度:0的元素被认为是可见的,因为它们仍然在布局中占用空间(如jQuery:可见选择器所描述的)——我们可以这样检查元素是否真的可见:
function isElementReallyHidden (el) {
return $(el).is(":hidden") || $(el).css("visibility") == "hidden" || $(el).css('opacity') == 0;
}
var booElementReallyShowed = !isElementReallyHidden(someEl);
$(someEl).parents().each(function () {
if (isElementReallyHidden(this)) {
booElementReallyShowed = false;
}
});
#26
26
if($('#postcode_div').is(':visible')) {
if($('#postcode_text').val()=='') {
$('#spanPost').text('\u00a0');
} else {
$('#spanPost').text($('#postcode_text').val());
}
#27
26
But what if the element's CSS is like the following?
但是如果元素的CSS像下面这样呢?
.element{
position: absolute;left:-9999;
}
So this answer to Stack Overflow question How to check if an element is off-screen should also be considered.
因此,对于堆栈溢出问题的回答也应该考虑如何检查元素是否在屏幕之外。
#28
25
A function can be created in order to check for visibility/display attributes in order to gauge whether the element is shown in the UI or not.
可以创建一个函数来检查可见性/显示属性,以判断元素是否显示在UI中。
function checkUIElementVisible(element) {
return ((element.css('display') !== 'none') && (element.css('visibility') !== 'hidden'));
}
工作小提琴
#29
25
Simply check visibility by checking for a boolean value, like:
通过检查布尔值来检查可见性,例如:
if (this.hidden === false) {
// Your code
}
I used this code for each function. Otherwise you can use is(':visible')
for checking the visibility of an element.
我为每个函数使用了这个代码。否则,您可以使用is(':visible')来检查元素的可见性。
#30
24
Also here's a ternary conditional expression to check the state of the element and then to toggle it:
这里还有一个三元条件表达式来检查元素的状态然后切换它:
$('someElement').on('click', function(){ $('elementToToggle').is(':visible') ? $('elementToToggle').hide('slow') : $('elementToToggle').show('slow'); });
#1
8212
Since the question refers to a single element, this code might be more suitable:
由于问题涉及单个元素,因此本代码可能更适合:
// Checks css for display:[none|block], ignores visibility:[true|false]
$(element).is(":visible");
Same as twernt's suggestion, but applied to a single element; and it matches the algorithm recommended in the jQuery FAQ
与twernt的建议相同,但适用于单个元素;它匹配jQuery FAQ中推荐的算法
#2
1249
You can use the hidden
selector:
您可以使用隐藏选择器:
// Matches all elements that are hidden
$('element:hidden')
And the visible
selector:
可见选择器:
// Matches all elements that are visible
$('element:visible')
#3
774
if ( $(element).css('display') == 'none' ){
// element is hidden
}
Functions don't work with the visibility attribute.
函数不使用可见性属性。
#4
444
None of these answers address what I understand to be the question, which is what I was searching for, "How do I handle items that have visibility: hidden
?". Neither :visible
nor :hidden
will handle this, as they are both looking for display per the documentation. As far as I could determine, there is no selector to handle CSS visibility. Here is how I resolved it (standard jQuery selectors, there may be a more condensed syntax):
这些答案都没有回答我所理解的问题,也就是我正在寻找的问题:“我如何处理具有可见性的项目:隐藏?”none:visible和:hidden将处理这个,因为它们都在根据文档查找显示。就我所知,没有选择器来处理CSS可见性。下面是我解析它的方法(标准jQuery选择器,可能有更简洁的语法):
$(".item").each(function() {
if ($(this).css("visibility") == "hidden") {
// handle non visible state
} else {
// handle visible state
}
});
#5
317
From How do I determine the state of a toggled element?
如何确定要切换的元素的状态?
You can determine whether an element is collapsed or not by using the :visible
and :hidden
selectors.
可以使用:visible和:hidden选择器来确定元素是否已折叠。
var isVisible = $('#myDiv').is(':visible');
var isHidden = $('#myDiv').is(':hidden');
If you're simply acting on an element based on its visibility, you can just include :visible
or :hidden
in the selector expression. For example:
如果您只是根据元素的可见性对其进行操作,那么可以在选择器表达式中包含:visible或:hidden。例如:
$('#myDiv:visible').animate({left: '+=200px'}, 'slow');
#6
232
Often when checking if something is visible or not, you are going to go right ahead immediately and do something else with it. jQuery chaining makes this easy.
通常,当检查某物是否可见时,您将立即进行操作,并对其进行其他操作。jQuery链接让这变得简单。
So if you have a selector and you want to perform some action on it only if is visible or hidden, you can use filter(":visible")
or filter(":hidden")
followed by chaining it with the action you want to take.
因此,如果您有一个选择器,并且您想要对它执行一些操作,只有在它是可见的或隐藏的时候,您可以使用filter(“:visible”)或filter(“:hidden”),然后用您想要执行的操作对它进行链接。
So instead of an if
statement, like this:
所以不是if语句,像这样
if ($('#btnUpdate').is(":visible"))
{
$('#btnUpdate').animate({ width: "toggle" }); // Hide button
}
Or more efficient, but even uglier:
或者更有效,但更丑:
var button = $('#btnUpdate');
if (button.is(":visible"))
{
button.animate({ width: "toggle" }); // Hide button
}
You can do it all in one line:
你可以用一句话来做:
$('#btnUpdate').filter(":visible").animate({ width: "toggle" });
#7
184
The :visible
selector according to the jQuery documentation:
根据jQuery文档可见选择器:
- They have a CSS
display
value ofnone
.- 它们的CSS显示值为none。
- They are form elements with
type="hidden"
.- 它们是带有type="hidden"的表单元素。
- Their width and height are explicitly set to 0.
- 它们的宽度和高度被显式设置为0。
- An ancestor element is hidden, so the element is not shown on the page.
- 一个祖先元素被隐藏,所以元素不会显示在页面上。
Elements with
visibility: hidden
oropacity: 0
are considered to be visible, since they still consume space in the layout.具有可见性的元素:隐藏或不透明:0被认为是可见的,因为它们仍然在布局中占用空间。
This is useful in some cases and useless in others, because if you want to check if the element is visible (display != none
), ignoring the parents visibility, you will find that doing .css("display") == 'none'
is not only faster, but will also return the visibility check correctly.
这在某些情况下是有用的,在其他情况下是无用的,因为如果您想检查元素是否可见(display != none),忽略父元素的可见性,您将发现执行.css(“display”)= 'none'不仅速度更快,而且还会正确地返回可见性检查。
If you want to check visibility instead of display, you should use: .css("visibility") == "hidden"
.
如果要检查可见性而不是显示,应该使用:.css(“visibility”)==“hidden”。
Also take into consideration the additional jQuery notes:
还要考虑到jQuery新增的注释:
Because
:visible
is a jQuery extension and not part of the CSS specification, queries using:visible
cannot take advantage of the performance boost provided by the native DOMquerySelectorAll()
method. To achieve the best performance when using:visible
to select elements, first select the elements using a pure CSS selector, then use.filter(":visible")
.因为:visible是jQuery扩展,而不是CSS规范的一部分,使用:visible的查询无法利用本机DOM querySelectorAll()方法提供的性能提升。要在使用:visible时实现最佳性能以选择元素,首先使用纯CSS选择器选择元素,然后使用.filter(“:visible”)。
Also, if you are concerned about performance, you should check Now you see me… show/hide performance (2010-05-04). And use other methods to show and hide elements.
另外,如果你担心性能,你应该检查你看到我了…显示/隐藏性能(2010-05-04)。并使用其他方法来显示和隐藏元素。
#8
165
This works for me, and I am using show()
and hide()
to make my div hidden/visible:
这对我来说是可行的,我使用show()和hide()使我的div隐藏/可见:
if( $(this).css('display') == 'none' ){
/* your code goes here */
} else {
/* alternate logic */
}
#9
163
How element visibility and jQuery works;
元素可见性和jQuery如何工作;
An element could be hidden with display:none
, visibility:hidden
or opacity:0
. The difference between those methods:
元素可以用display:none、visibility:hidden或透明度:0隐藏。这些方法的区别是:
-
display:none
hides the element, and it does not take up any space; - 显示:没有隐藏元素,它不占用任何空间;
-
visibility:hidden
hides the element, but it still takes up space in the layout; - 可见性:隐藏隐藏元素,但仍然占用布局空间;
-
opacity:0
hides the element as "visibility:hidden", and it still takes up space in the layout; the only difference is that opacity lets one to make an element partly transparent;不透明度:0将元素隐藏为“可见性:隐藏”,仍然占据布局空间;唯一的区别是不透明可以让一个元素部分透明;
if ($('.target').is(':hidden')) { $('.target').show(); } else { $('.target').hide(); } if ($('.target').is(':visible')) { $('.target').hide(); } else { $('.target').show(); } if ($('.target-visibility').css('visibility') == 'hidden') { $('.target-visibility').css({ visibility: "visible", display: "" }); } else { $('.target-visibility').css({ visibility: "hidden", display: "" }); } if ($('.target-visibility').css('opacity') == "0") { $('.target-visibility').css({ opacity: "1", display: "" }); } else { $('.target-visibility').css({ opacity: "0", display: "" }); }
Useful jQuery toggle methods:
有用的jQuery切换方法:
$('.click').click(function() { $('.target').toggle(); }); $('.click').click(function() { $('.target').slideToggle(); }); $('.click').click(function() { $('.target').fadeToggle(); });
#10
131
I would use CSS class .hide { display: none!important; }
.
我将使用CSS类。hide {display: none!important;}。
For hiding/showing, I call .addClass("hide")/.removeClass("hide")
. For checking visibility, I use .hasClass("hide")
.
为了隐藏/显示,我调用。addclass(“隐藏”)/. removeclass(“隐藏”)。为了检查可见性,我使用. hasclass(“隐藏”)。
It's a simple and clear way to check/hide/show elements, if you don't plan to use .toggle()
or .animate()
methods.
如果不打算使用.toggle()或.animate()方法,这是一种检查/隐藏/显示元素的简单而清晰的方法。
#11
125
You can also do this using plain JavaScript:
你也可以使用普通的JavaScript:
function isRendered(domObj) {
if ((domObj.nodeType != 1) || (domObj == document.body)) {
return true;
}
if (domObj.currentStyle && domObj.currentStyle["display"] != "none" && domObj.currentStyle["visibility"] != "hidden") {
return isRendered(domObj.parentNode);
} else if (window.getComputedStyle) {
var cs = document.defaultView.getComputedStyle(domObj, null);
if (cs.getPropertyValue("display") != "none" && cs.getPropertyValue("visibility") != "hidden") {
return isRendered(domObj.parentNode);
}
}
return false;
}
Notes:
注:
-
Works everywhere
工作无处不在
-
Works for nested elements
适合嵌套的元素
-
Works for CSS and inline styles
适用于CSS和内联样式。
-
Doesn't require a framework
不需要一个框架
#12
104
One can simply use the hidden
or visible
attribute, like:
可以简单地使用隐藏或可见属性,如:
$('element:hidden')
$('element:visible')
Or you can simplify the same with is as follows.
或者你也可以化简如下。
$(element).is(":visible")
#13
97
Another answer you should put into consideration is if you are hiding an element, you should use jQuery, but instead of actually hiding it, you remove the whole element, but you copy its HTML content and the tag itself into a jQuery variable, and then all you need to do is test if there is such a tag on the screen, using the normal if (!$('#thetagname').length)
.
你应该考虑另一个答案是如果你隐藏一个元素,您应该使用jQuery,但实际上隐藏它,而是你删除整个元素,但你复制它的HTML内容和标签本身变成一个jQuery变量,然后你需要做的就是测试如果有这样一个标签在屏幕上,使用正常,如果(! $(' # thetagname '). length)。
#14
90
ebdiv
should be set to style="display:none;"
. It is works for show and hide:
ebdiv应该设置为style="display:none;"。它是用来展示和隐藏的:
$(document).ready(function(){
$("#eb").click(function(){
$("#ebdiv").toggle();
});
});
#15
90
$('#clickme').click(function() {
$('#book').toggle('slow', function() {
// Animation complete.
alert($('#book').is(":visible")); //<--- TRUE if Visible False if Hidden
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clickme">
Click here
</div>
<img id="book" src="http://www.chromefusion.com/wp-content/uploads/2012/06/chrome-logo.jpg" alt="" />
Source:
来源:
Blogger n Play - jQuery工具和小部件:如何使用jQuery查看元素是否隐藏或可见
jsFiddle:
jsFiddle:
JSFiddle - ipsjolly - k4WWj
#16
78
When testing an element against :hidden
selector in jQuery it should be considered that an absolute positioned element may be recognized as hidden although their child elements are visible.
在jQuery中测试一个元素时,应该考虑到一个绝对定位元素可以被识别为隐藏的,尽管它们的子元素是可见的。
This seems somewhat counter-intuitive in the first place – though having a closer look at the jQuery documentation gives the relevant information:
乍一看,这似乎有点反直觉——不过仔细看看jQuery文档就会得到相关信息:
Elements can be considered hidden for several reasons: [...] Their width and height are explicitly set to 0. [...]
可以认为元素隐藏有以下几个原因:它们的宽度和高度被显式地设置为0。[…]
So this actually makes sense in regards to the box-model and the computed style for the element. Even if width and height are not set explicitly to 0 they may be set implicitly.
这对于方框模型和元素的计算风格来说是有意义的。即使宽度和高度没有显式地设置为0,也可以隐式地设置它们。
Have a look at the following example:
请看下面的例子:
console.log($('.foo').is(':hidden')); // true
console.log($('.bar').is(':hidden')); // false
.foo {
position: absolute;
left: 10px;
top: 10px;
background: #ff0000;
}
.bar {
position: absolute;
left: 10px;
top: 10px;
width: 20px;
height: 20px;
background: #0000ff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">
<div class="bar"></div>
</div>
UPDATE FOR JQUERY 3.x:
更新JQUERY 3. x:
With jQuery 3 the described behavior will change! Elements will be considered visible if they have any layout boxes, including those of zero width and/or height.
使用jQuery 3,所描述的行为将会改变!如果元素有任何布局框(包括零宽度和/或高度),则将被认为是可见的。
JSFiddle with jQuery 3.0.0-alpha1:
与jQuery 3.0.0-alpha1 JSFiddle:
http://jsfiddle.net/pM2q3/7/
The same JS will then have this output:
同样的JS将会有这样的输出:
console.log($('.foo').is(':hidden')); // false
console.log($('.bar').is(':hidden')); // false
#17
75
This may work:
这可能工作:
expect($("#message_div").css("display")).toBe("none");
#18
55
To check if it is not visible I use !
:
检查它是否不可见,我使用!
if ( !$('#book').is(':visible')) {
alert('#book is not visible')
}
Or the following is also the sam, saving the jQuery selector in a variable to have better performance when you need it multiple times:
或者下面是sam,在需要多次使用时,将jQuery选择器保存在一个变量中以获得更好的性能:
var $book = $('#book')
if(!$book.is(':visible')) {
alert('#book is not visible')
}
#19
55
Example:
例子:
$(document).ready(function() {
if ($("#checkme:hidden").length) {
console.log('Hidden');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="checkme" class="product" style="display:none">
<span class="itemlist"><!-- Shows Results for Fish --></span> Category:Fish
<br>Product: Salmon Atlantic
<br>Specie: Salmo salar
<br>Form: Steaks
</div>
#20
53
Use class toggling, not style editing . . .
Using classes designated for "hiding" elements is easy and also one of the most efficient methods. Toggling a class 'hidden' with a Display
style of 'none' will perform faster than editing that style directly. I explained some of this pretty thoroughly in Stack Overflow question Turning two elements visible/hidden in the same div.
使用为“隐藏”元素指定的类很容易,也是最有效的方法之一。使用'none'显示样式切换类'hidden'将比直接编辑该样式执行得更快。我在Stack Overflow中详细介绍了其中的一些问题,将两个元素隐藏在同一个div中。
JavaScript Best Practices and Optimization
Here is a truly enlightening video of a Google Tech Talk by Google front-end engineer Nicholas Zakas:
下面是谷歌前端工程师尼古拉斯·扎卡斯主持的谷歌技术讲座的一个非常有启发性的视频:
- Speed Up Your Javascript (YouTube)
- 加快你的Javascript (YouTube)
#21
52
Example of using the visible check for adblocker is activated:
使用可见检查adblocker的例子被激活:
$(document).ready(function(){
if(!$("#ablockercheck").is(":visible"))
$("#ablockermsg").text("Please disable adblocker.").show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ad-placement" id="ablockercheck"></div>
<div id="ablockermsg" style="display: none"></div>
"ablockercheck" is a ID which adblocker blocks. So checking it if it is visible you are able to detect if adblocker is turned On.
“ablockercheck”是adblocker阻塞的ID。所以检查它是否可见你可以检测adblocker是否被打开。
#22
49
After all, none of examples suits me, so I wrote my own.
毕竟,没有一个例子适合我,所以我自己写了。
Tests (no support of Internet Explorer filter:alpha
):
测试(不支持ie滤镜:alpha):
a) Check if the document is not hidden
a)检查文件是否未隐藏
b) Check if an element has zero width / height / opacity or display:none
/ visibility:hidden
in inline styles
b)检查一个元素是否有零宽度/高度/不透明度或显示:无/可见性:隐藏在内联样式中
c) Check if the center (also because it is faster than testing every pixel / corner) of element is not hidden by other element (and all ancestors, example: overflow:hidden
/ scroll / one element over enother) or screen edges
c)检查元素的中心(也因为它比测试每个像素/角都快)是否没有被其他元素(以及所有祖先元素,例如:overflow:hidden / scroll / one element over other)或屏幕边缘隐藏
d) Check if an element has zero width / height / opacity or display:none
/ visibility:hidden in computed styles (among all ancestors)
d)检查元素是否为零宽度/高度/不透明度或显示:无/可见性:隐藏在计算样式中(在所有祖先中)
Tested on
测试
Android 4.4 (Native browser/Chrome/Firefox), Firefox (Windows/Mac), Chrome (Windows/Mac), Opera (Windows Presto/Mac Webkit), Internet Explorer (Internet Explorer 5-11 document modes + Internet Explorer 8 on a virtual machine), Safari (Windows/Mac/iOS)
Android 4.4(本机浏览器/Chrome/Firefox)、Firefox (Windows/Mac)、Chrome (Windows/Mac)、Opera (Windows Presto/Mac Webkit)、Internet Explorer (Internet Explorer 5-11文档模式+ Internet Explorer 8虚拟机)、Safari (Windows/Mac/iOS)
var is_visible = (function () {
var x = window.pageXOffset ? window.pageXOffset + window.innerWidth - 1 : 0,
y = window.pageYOffset ? window.pageYOffset + window.innerHeight - 1 : 0,
relative = !!((!x && !y) || !document.elementFromPoint(x, y));
function inside(child, parent) {
while(child){
if (child === parent) return true;
child = child.parentNode;
}
return false;
};
return function (elem) {
if (
document.hidden ||
elem.offsetWidth==0 ||
elem.offsetHeight==0 ||
elem.style.visibility=='hidden' ||
elem.style.display=='none' ||
elem.style.opacity===0
) return false;
var rect = elem.getBoundingClientRect();
if (relative) {
if (!inside(document.elementFromPoint(rect.left + elem.offsetWidth/2, rect.top + elem.offsetHeight/2),elem)) return false;
} else if (
!inside(document.elementFromPoint(rect.left + elem.offsetWidth/2 + window.pageXOffset, rect.top + elem.offsetHeight/2 + window.pageYOffset), elem) ||
(
rect.top + elem.offsetHeight/2 < 0 ||
rect.left + elem.offsetWidth/2 < 0 ||
rect.bottom - elem.offsetHeight/2 > (window.innerHeight || document.documentElement.clientHeight) ||
rect.right - elem.offsetWidth/2 > (window.innerWidth || document.documentElement.clientWidth)
)
) return false;
if (window.getComputedStyle || elem.currentStyle) {
var el = elem,
comp = null;
while (el) {
if (el === document) {break;} else if(!el.parentNode) return false;
comp = window.getComputedStyle ? window.getComputedStyle(el, null) : el.currentStyle;
if (comp && (comp.visibility=='hidden' || comp.display == 'none' || (typeof comp.opacity !=='undefined' && comp.opacity != 1))) return false;
el = el.parentNode;
}
}
return true;
}
})();
How to use:
如何使用:
is_visible(elem) // boolean
#23
46
You need to check both... Display as well as visibility:
你需要同时检查两个……显示和可见性:
if ($(this).css("display") == "none" || $(this).css("visibility") == "hidden") {
// The element is not visible
} else {
// The element is visible
}
If we check for $(this).is(":visible")
, jQuery checks for both the things automatically.
如果我们检查$(this).is(":visible"), jQuery会自动地检查这两项。
#24
34
Maybe you can do something like this
也许你可以做这样的事情。
$(document).ready(function() {
var visible = $('#tElement').is(':visible');
if(visible) {
alert("visible");
// Code
}
else
{
alert("hidden");
}
});
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<input type="text" id="tElement" style="display:block;">Firstname</input>
#25
29
Because Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout
(as described for jQuery :visible Selector) - we can check if element is really visible in this way:
因为具有可见性:隐藏或不透明度:0的元素被认为是可见的,因为它们仍然在布局中占用空间(如jQuery:可见选择器所描述的)——我们可以这样检查元素是否真的可见:
function isElementReallyHidden (el) {
return $(el).is(":hidden") || $(el).css("visibility") == "hidden" || $(el).css('opacity') == 0;
}
var booElementReallyShowed = !isElementReallyHidden(someEl);
$(someEl).parents().each(function () {
if (isElementReallyHidden(this)) {
booElementReallyShowed = false;
}
});
#26
26
if($('#postcode_div').is(':visible')) {
if($('#postcode_text').val()=='') {
$('#spanPost').text('\u00a0');
} else {
$('#spanPost').text($('#postcode_text').val());
}
#27
26
But what if the element's CSS is like the following?
但是如果元素的CSS像下面这样呢?
.element{
position: absolute;left:-9999;
}
So this answer to Stack Overflow question How to check if an element is off-screen should also be considered.
因此,对于堆栈溢出问题的回答也应该考虑如何检查元素是否在屏幕之外。
#28
25
A function can be created in order to check for visibility/display attributes in order to gauge whether the element is shown in the UI or not.
可以创建一个函数来检查可见性/显示属性,以判断元素是否显示在UI中。
function checkUIElementVisible(element) {
return ((element.css('display') !== 'none') && (element.css('visibility') !== 'hidden'));
}
工作小提琴
#29
25
Simply check visibility by checking for a boolean value, like:
通过检查布尔值来检查可见性,例如:
if (this.hidden === false) {
// Your code
}
I used this code for each function. Otherwise you can use is(':visible')
for checking the visibility of an element.
我为每个函数使用了这个代码。否则,您可以使用is(':visible')来检查元素的可见性。
#30
24
Also here's a ternary conditional expression to check the state of the element and then to toggle it:
这里还有一个三元条件表达式来检查元素的状态然后切换它:
$('someElement').on('click', function(){ $('elementToToggle').is(':visible') ? $('elementToToggle').hide('slow') : $('elementToToggle').show('slow'); });