JQuery:如果 div 可见 [英] JQuery: if div is visible

查看:19
本文介绍了JQuery:如果 div 可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 JS 作为更改我创建的 SPA 内容的一种方式.当我按下一个按钮来更改内容时,HTML 从此更改:

为此:

现在我的 SPA 的一部分有一个包含多个复选框的 div,每个复选框代表一个 div,因此当我按下提交按钮时,应该显示的下一个 div 将是复选框列表中的第一个项目已选中.

我想知道 JQuery 中是否有一种方法可以让代码几乎检测"哪个 div 现在可见.像这样:

if($('#selectDiv').isVisible()){//与这个div关联的JS代码.}

有什么建议吗?

解决方案

您可以使用 .is(':visible')

<块引用>

选择所有可见的元素.

例如:

if($('#selectDiv').is(':visible')){

此外,您可以通过以下方式获取可见的 div:

$('div:visible').callYourFunction();

现场示例:

console.log($('#selectDiv').is(':visible'));console.log($('#visibleDiv').is(':visible'));

#selectDiv {显示:无;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div id="selectDiv"></div><div id="visibleDiv"></div>

I'm using JS as a way of changing the content of an SPA I'm creating. When I press a button to change the content the HTML changes from this:

<div id="selectDiv" style="display: none;">

to this:

<div id="selectDiv" style>

Now part of my SPA has a div that contains a number of checkboxes, each representing a div, and so when I press the submit button, the next div that should be displayed will be the first item in the checkbox list that was selected.

I'm wondering if there's a way in JQuery for the code to "almost detect" which div is now visible. something like this:

if($('#selectDiv').isVisible()){
    //JS code associated with this div.
}

Any suggestions?

解决方案

You can use .is(':visible')

Selects all elements that are visible.

For example:

if($('#selectDiv').is(':visible')){

Also, you can get the div which is visible by:

$('div:visible').callYourFunction();

Live example:

console.log($('#selectDiv').is(':visible'));
console.log($('#visibleDiv').is(':visible'));

#selectDiv {
  display: none;  
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="selectDiv"></div>
<div id="visibleDiv"></div>

这篇关于JQuery:如果 div 可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆