非jQuery相当于:在JavaScript中可见?

因此,jQuery在DOM上提供了这个非常棒的伪查询’:visible’,不幸的是,它与jQuery和Sizzle(或者你可能使用的任何引擎)的核心相关联。 当只知道给定元素时,在纯JavaScript中有一个很好的等价物吗?

关于jQuery的提醒:可见规则:

  • 它们的CSS显示值为none。
  • 它们是type =“hidden”的表单元素。
  • 它们的宽度和高度显式设置为0。

隐藏了一个祖先元素,因此该元素不会显示在页面上。

注意:只检查给定元素的样式并不总是有效:可能隐藏父项而不是隐藏所有子项。

您可以从源代码中获取相关代码 :

 jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight; return ( width === 0 && height === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; 
  • jQuery.css可以替换为getComputedStyle (或IE的.currentStyle )。
  • jQuery.support.reliableHiddenOffsets是一个变量,用于确定属性是否可靠(IE8-)。

我只是先查看jquery,因为它是JavaScript。 这是实际的代码:

 if ( jQuery.expr && jQuery.expr.filters ) { // here is the real guts of it jQuery.expr.filters.hidden = function( elem ) { // plain old JavaScript determining offset var width = elem.offsetWidth, height = elem.offsetHeight; // if any of these are "true" then its "invisible" return ( width === 0 && height === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; // this is just checking for not hidden jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } 

“reliableHiddenOffsets”代码在此之前定义,您可以在下面看到它

 isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE <= 8 fail this test) support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); 

这里真正的教训是这些东西不是火箭科学。 破解打开jQuery并看一看。 jQuery的真正gem是它经过了如此严格的测试和攻击,你可能不会发现任何问题。 除了伟大的选择器引擎和抽象之外,这非常值得。 不要害怕实际看。 你会在这个过程中学到一些很好的副作用。

我建议你至少使用一些选择器库来完成这项工作。 否则,你只是在已经经过测试并且没有特殊原因certificate成功的事情上浪费你的努力,而且你可能甚至在你做的前几次尝试中都弄错了。

例如, Sizzle在缩小/压缩时只有4kb,所以我几乎没有理由不使用它。