使用 jQuery 获取第一个可见元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18162689/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:08:56  来源:igfitidea点击:

Getting first visible element with jQuery

jqueryjquery-selectors

提问by Yarin

Trying to get the first visible element of a list using jQuery's :firstand :visiblepseudo-selectors, as suggested here: https://stackoverflow.com/a/830611/165673but it's not working:

尝试使用 jQuery:first:visible伪选择器获取列表的第一个可见元素,如下所示:https: //stackoverflow.com/a/830611/165673但它不起作用:

Fiddle:http://jsfiddle.net/FAY9q/4/

小提琴:http : //jsfiddle.net/FAY9q/4/

HTML:

HTML:

<ul>
    <li>Item A</li>
    <li>Item B</li>
    <li>Item C</li>
</ul>
<ul>
    <li style="display:none;">Item A</li>
    <li>Item B</li>
    <li>Item C</li>
</ul>

JQUERY:

查询:

$('li:visible:first').css('background','blue');

The first item in each list should turn blue...

每个列表中的第一项应该变成蓝色...

回答by Joe

Try using this:

尝试使用这个:

$('ul').find('li:visible:first').css('background','blue');

Currently your code is just getting the first visible lielement on the page and setting the background colour. This code selects all ulelements then finds the first visible liwithin each of them and applies the style.

目前您的代码只是获取li页面上的第一个可见元素并设置背景颜色。此代码选择所有ul元素,然后li在每个元素中找到第一个可见的元素并应用样式。

Here it is working: http://jsfiddle.net/FAY9q/5/

它正在工作:http: //jsfiddle.net/FAY9q/5/

回答by user3353523

What about using this:

使用这个怎么样:

li:visible:not(:visible ~ :visible)

回答by Pranay Bhardwaj

$('li:visible').eq(0).css('background','blue');