是图像可见或不可见

问题描述:

测试假如我用代码获取的图像是对用户可见或不是图像可见或不可见

限制

  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;} 
} 

尝试采取风格检查的其他外部计算样式条件句。我们要同时检查内嵌样式和计算样式

改变(从样式表。):

else if (window.getComputedStyle) { 

要:

if (window.getComputedStyle) { 

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

+0

这是令人尴尬的。这是我自己的编辑,打破了:( – mplungjan 2011-12-20 08:20:19