Javascript:如何检查元素是否可见?

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

Javascript: How to check if element is visible?

javascriptjqueryselectorvisiblezepto

提问by matt

i'm using the lightweight zepto.js framework and now I need to test if an element on the page is visible or not … this my case:

我正在使用轻量级 zepto.js 框架,现在我需要测试页面上的元素是否可见……这是我的情况:

A button triggers the function show_guides().

一个按钮触发该功能show_guides()

function show_guides() {
    $('#guides').toggle();

    if ( $('#guides').is(':visible') ) { // does not work
        //$.cookie('guides_visible', 'true');
        console.log("visible");
    } else {
        console.log("invisible");
        //$.cookie('guides_visible', null);
    }
}

If the $('#guides')are visible I want to save a cookie and if they are not I want to get rid of it.

如果$('#guides')它们可见,我想保存一个 cookie,如果它们不可见,我想摆脱它。

However zepto.js doesn't support selectors like :visibleso I have to find a different way. Any ideas how to do that? Right now I'm getting the following error:

但是 zepto.js 不支持选择器,:visible所以我必须找到一种不同的方式。任何想法如何做到这一点?现在我收到以下错误:

Uncaught Error: SYNTAX_ERR: DOM Exception 12

未捕获的错误:SYNTAX_ERR:DOM 异常 12

In the zepto documentation i've read this?…

在 zepto 文档中我读过这个?...

For basic support of jQuery's non-standard pseudo-selectors such as :visible, include the optional “selector” module.

对于 jQuery 的非标准伪选择器(例如 :visible)的基本支持,请包含可选的“选择器”模块。

But I have no idea how to include this.

但我不知道如何包括这个。

Anybody out the who could help me out here? Thank you in advance.

有谁能帮帮我吗?先感谢您。

回答by sdespont

You can check the display CSS property:

您可以检查 display CSS 属性:

 function show_guides() {

        $('#guides').toggle();

        if ( $('#guides').css('display') == 'block' ) { 
            console.log("visible");
        } else {
            console.log("invisible");
        }
    }

回答by Avinash

try

尝试

     style.display="block";

and

     style.display="hidden";

回答by fedmich

You can check visibility:visible/hidden, or display:block/none

您可以检查可见性:可见/隐藏,或显示:阻止/无

$('#guides').css('visibility') == 'visible'
$('#guides').css('display') == 'block'

回答by Zaptree

If all you want is to check visibility you can just use this

如果您只想检查可见性,您可以使用它

  function visible(elem){
    elem = $(elem)
    return !!(elem.width() || elem.height()) && elem.css("display") !== "none"
  }

taken straight from the zepto selectors plugin. Otherwise you can just include the selectors module from https://github.com/madrobby/zepto/blob/master/src/selector.jsas Felix Kling suggested

直接取自 zepto 选择器插件。否则,您可以按照 Felix Kling 的建议从https://github.com/madrobby/zepto/blob/master/src/selector.js 中包含选择器模块