2011-12-20 113 views
0

測試假如我用代碼獲取的圖像是對用戶可見或不是圖像可見或不可見

限制

  1. 普通的JavaScript - 請不建議jQuery或其他框架

  2. 我只對display:none和感興趣3210但不透明度和這樣當然是歡迎

代碼:下面(從here拍攝)並不在我的DEMO

問題的工作:你能幫使得無論是工作或建議一個更好的腳本?

版本A

function isVisible(obj){ 
    if (obj == document) return true; 
    if (!obj) return false; 
    if (!obj.parentNode) return false; 
    if (obj.style) { 
    if (obj.style.display == 'none' || obj.style.visibility == 'hidden') return false; 
    } 
    else if (window.getComputedStyle) { // MY BAD - I PUT THE INCORRECT ELSE HERE 
    var style = window.getComputedStyle(obj, ""); 
    if (style.display == 'none' || style.visibility == 'hidden') return false; 
    } 
    else if (obj.currentStyle) { 
    var style = obj.currentStyle; 
    if (style['display'] == 'none' || style['visibility'] == 'hidden') return false; 
    } 
    return isVisible(obj.parentNode); 
} 

版本B

function isVisible1(obj) { 
    var cnode = obj; 
    try { 
    while(cnode) { 
     if (cnode.nodeName) { 
     if (cnode.nodeName.toLowerCase()=="body") { 
      return true; 
     } 
     } 
     if (cnode.style.display=="none" || cnode.style.visibility=="hidden") { 
     return false; 
     } 
     cnode = cnode.parentNode; 
    } 
    return true; 
    } 
    catch(ex) {return false;} 
} 

回答

1

嘗試採取風格檢查的其他外部計算樣式條件句。我們要同時檢查內嵌樣式和計算樣式

改變(從樣式表。):

else if (window.getComputedStyle) { 

要:

if (window.getComputedStyle) { 

歧路小提琴:http://jsfiddle.net/MXgbh/1/

+0

這是令人尷尬的。這是我自己的編輯,打破了:( – mplungjan 2011-12-20 08:20:19