检查元素在DOM中是否可见

本文翻译自:Check if element is visible in DOM

Is there any way that I can check if an element is visible in pure JS (no jQuery) ? 有什么方法可以检查元素在纯JS(无jQuery)中是否可见?

So, for example, in this page: Performance Bikes , if you hover over Deals (on the top menu), a window of deals appear, but at the beginning it was not shown. 因此,例如,在此页面: Performance Bikes中 ,如果将鼠标悬停在Deals上(在顶部菜单上),则会显示一个交易窗口,但一开始并未显示。 It is in the HTML but it is not visible. 它在HTML中,但不可见。

So, given a DOM element, how can I check if it is visible or not? 那么,给定一个DOM元素,如何检查它是否可见? I tried: 我试过了:

window.getComputedStyle(my_element)['display']);

but it doesn't seem to be working. 但它似乎不起作用。 I wonder which attributes should I check. 我想知道应该检查哪些属性。 It comes to my mind: 我想到:

display !== 'none'
visibility !== 'hidden'

Any others that I might be missing? 还有其他我可能会想念的东西吗?


#1楼

参考:https://stackoom.com/question/1KX0c/检查元素在DOM中是否可见


#2楼

This may help : Hide the element by positioning it on far most left position and then check the offsetLeft property. 这可能会有所帮助:通过将元素放置在最左边的位置来隐藏该元素,然后检查offsetLeft属性。 If you want to use jQuery you can simply check the :visible selector and get the visibility state of the element. 如果要使用jQuery,则可以简单地检查:visible选择器并获取元素的可见性状态。

HTML : HTML:

<div id="myDiv">Hello</div>

CSS : CSS:

<!-- for javaScript-->
#myDiv{
   position:absolute;
   left : -2000px;
}

<!-- for jQuery -->
#myDiv{
    visibility:hidden;
}

javaScript : javaScript:

var myStyle = document.getElementById("myDiv").offsetLeft;

if(myStyle < 0){
     alert("Div is hidden!!");
}

jQuery : jQuery的:

if(  $("#MyElement").is(":visible") == true )
{  
     alert("Div is hidden!!");        
}

jsFiddle jsFiddle


#3楼

If we're just collecting basic ways of detecting visibility, let me not forget: 如果我们只是收集检测可见性的基本方法,请不要忘记:

opacity > 0.01; // probably more like .1 to actually be visible, but YMMV

And as to how to obtain attributes: 关于如何获取属性:

element.getAttribute(attributename);

So, in your example: 因此,在您的示例中:

document.getElementById('snDealsPanel').getAttribute('visibility');

But wha? 但是呢? It doesn't work here. 它在这里不起作用。 Look closer and you'll find that visibility is being updated not as an attribute on the element, but using the style property. 仔细观察,您会发现可见性不是作为元素的属性而是使用style属性进行更新。 This is one of many problems with trying to do what you're doing. 这是尝试做自己正在做的许多问题之一。 Among others: you can't guarantee that there's actually something to see in an element, just because its visibility, display, and opacity all have the correct values. 其中:您不能保证元素中确实有东西要看,因为它的可见性,显示性和不透明度都具有正确的值。 It still might lack content, or it might lack a height and width. 它仍然可能缺少内容,或者可能缺少高度和宽度。 Another object might obscure it. 另一个物体可能会使其模糊。 For more detail, a quick Google search reveals this , and even includes a library to try solving the problem. 要获取更多详细信息,可以通过Google的快速搜索找到此内容 ,甚至包括一个尝试解决问题的库。 (YMMV) (YMMV)

Check out the following, which are possible duplicates of this question, with excellent answers, including some insight from the mighty John Resig. 请查看以下内容,这些内容可能是该问题的重复部分,并且答案出色,包括强大的约翰·雷西格(John Resig)的一些见识。 However, your specific use-case is slightly different from the standard one, so I'll refrain from flagging: 但是,您的特定用例与标准用例略有不同,因此,我将避免标记:

(EDIT: OP SAYS HE'S SCRAPING PAGES, NOT CREATING THEM, SO BELOW ISN'T APPLICABLE) A better option? (编辑:OP表示他正在裁剪页面,而不创建页面,因此下面不适用)更好的选择吗? Bind the visibility of elements to model properties and always make visibility contingent on that model, much as Angular does with ng-show. 将元素的可见性绑定到模型属性,并使可见性始终取决于该模型,就像Angular对ng-show所做的一样。 You can do that using any tool you want: Angular, plain JS, whatever. 您可以使用所需的任何工具来做到这一点:Angular,普通的JS等。 Better still, you can change the DOM implementation over time, but you'll always be able to read state from the model, instead of the DOM. 更好的是,您可以随时间更改DOM的实现,但始终可以从模型而不是DOM中读取状态。 Reading your truth from the DOM is Bad. 从DOM读取您的真相是不好的。 And slow. 又慢 Much better to check the model, and trust in your implementation to ensure that the DOM state reflects the model. 检查模型好得多,并信任您的实现以确保DOM状态反映模型。 (And use automated testing to confirm that assumption.) (并使用自动测试来确认该假设。)


#4楼

According to this MDN documentation , an element's offsetParent property will return null whenever it, or any of its parents, is hidden via the display style property. 根据此MDN文档 ,每当offsetParent或元素的任何父offsetParent通过display style属性被隐藏时,该元素的offsetParent属性将返回null Just make sure that the element isn't fixed. 只要确保该元素未固定即可。 A script to check this, if you have no position: fixed; 如果没有position: fixed; ,请使用脚本来检查position: fixed; elements on your page, might look like: 页面上的元素可能看起来像:

// Where el is the DOM element you'd like to test for visibility
function isHidden(el) {
    return (el.offsetParent === null)
}

On the other hand, if you do have position fixed elements that might get caught in this search, you will sadly (and slowly) have to use window.getComputedStyle() . 另一方面,如果您确实有位置固定的元素可能会在此搜索中被捕获,您将不得不(缓慢地)使用window.getComputedStyle() The function in that case might be: 在这种情况下,功能可能是:

// Where el is the DOM element you'd like to test for visibility
function isHidden(el) {
    var style = window.getComputedStyle(el);
    return (style.display === 'none')
}

Option #2 is probably a little more straightforward since it accounts for more edge cases, but I bet its a good deal slower, too, so if you have to repeat this operation many times, best to probably avoid it. 选项#2可能更直接一些,因为它可以解决更多的情况,但是我敢打赌,它的速度也要慢得多,因此,如果您必须重复执行多次此操作,最好避免这种情况。


#5楼

The jQuery code from http://code.jquery.com/jquery-1.11.1.js has an isHidden param 来自http://code.jquery.com/jquery-1.11.1.js的jQuery代码具有isHidden参数

var isHidden = function( elem, el ) {
    // isHidden might be called from jQuery#filter function;
    // in that case, element will be second argument
    elem = el || elem;
    return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
};

So it looks like there is an extra check related to the owner document 因此,似乎存在与所有者文档相关的额外检查

I wonder if this really catches the following cases: 我想知道这是否确实包含以下情况:

  1. Elements hidden behind other elements based on zIndex 隐藏在基于zIndex的其他元素后面的元素
  2. Elements with transparency full making them invisible 透明的元素使它们不可见
  3. Elements positioned off screen (ie left: -1000px) 元素位于屏幕外(即,左:-1000px)
  4. Elements with visibility:hidden 具有可见性的元素:隐藏
  5. Elements with display:none 显示元素:无
  6. Elements with no visible text or sub elements 没有可见文本或子元素的元素
  7. Elements with height or width set to 0 高度或宽度设置为0的元素

#6楼

This is a way to determine it for all css properties including visibility: 这是一种针对所有CSS属性(包括可见性)确定它的方法:

html: 的HTML:

<div id="element">div content</div>

css: CSS:

#element
{
visibility:hidden;
}

javascript: javascript:

var element = document.getElementById('element');
 if(element.style.visibility == 'hidden'){
alert('hidden');
}
else
{
alert('visible');
}

It works for any css property and is very versatile and reliable. 它适用于任何CSS属性,并且用途广泛且可靠。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章