檢查元素在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屬性,並且用途廣泛且可靠。

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