javascript 仅获取未隐藏的元素.. Jquery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13949726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get only the elements which are not hidden.. Jquery
提问by Vinoth Babu
I need to get only the show() element in jquery foreach loop
我只需要在 jquery foreach 循环中获取 show() 元素
In the below code i am getting all the element with class test (i.e) both hidden and shown... but need only shown and not hidden one... how to filter and get that in this line itself?????
在下面的代码中,我得到了所有带有类测试的元素(即)隐藏和显示......但只需要显示而不是隐藏一个......如何过滤并在这一行中得到它????
$('.element').find('.test').each(function(index, loopelement) {
}
回答by Rory McCrossan
回答by Bruno
You can use jQuery's :visibleselector.
您可以使用jQuery 的 :visible选择器。
var $visibles = $(".element").find(".test:visible");
But be aware of how jQuery works. From jQuery documentation:
但请注意 jQuery 的工作原理。来自 jQuery 文档:
Elements are considered visible if they consume space in the document. Visible elements have a width or height that is greater than zero.
Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout.
如果元素占用文档中的空间,则元素被认为是可见的。可见元素的宽度或高度大于零。
具有可见性:隐藏或不透明度:0 的元素被认为是可见的,因为它们仍然占用布局中的空间。
In case this behaviour doesn't fit your use case you could extend jQuery, creating your own custom selector:
如果此行为不适合您的用例,您可以扩展 jQuery,创建您自己的自定义选择器:
$.expr[":"].reallyVisible =
function reallyVisible (elem) {
if (elem == null || elem.tagName == null) {
return false;
}
if (elem.tagName.toLowerCase() === "script" || elem.tagName.toLowerCase() === "input" && elem.type === "hidden") {
return false;
}
do {
if (!isVisible(elem)) {
return false;
}
elem = elem.parentNode;
} while (elem != null && elem.tagName.toLowerCase() !== "html");
return true;
};
function isVisible (elem) {
var style = elem.style;
// Depending on your use case
// you could check the height/width, or if it's in the viewport...
return !(style.display === "none" || style.opacity === "0" || style.visibility === "hidden");
}
It can be used as any other built-in selector:
它可以用作任何其他内置选择器:
$(".element").find(".test:reallyVisible");
$(".element").find(".test:first").is(":reallyVisible");