非jQuery相当于:在JavaScript中可见?
所以jQuery提供了这个令人敬畏的伪查询在':可见'的DOM,不幸的是,它与jQuery和Sizzle的核心(或任何你可能使用的引擎)相当紧密地联系在一起。当只有一个给定的元素是已知的时,在普通的JavaScript中是否有很好的等价物?非jQuery相当于:在JavaScript中可见?
了jQuery提醒一下:可见规则:
- 他们有没有的CSS显示值。
- 它们是type =“hidden”的表单元素。
- 及其宽度和高度被明确设置为0。
的祖先元素是隐藏的,所以该元件没有在网页上显示。
注意:只检查给定元素的样式并不总是有效:父项可能隐藏而不是隐藏所有子项。
您可以从该source code获得相关代码:
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
(或.currentStyle
用于IE)。 -
jQuery.support.reliableHiddenOffsets
是一个决定属性是否可靠的变量(IE8-)。
所以它不检查父母是否显示? – dynamic 2012-03-09 17:03:59
@ yes123当元素不可见时,'ofsetWidth'和'offsetHeight'属性为零。当父项不可见时,元素也不可见。 – 2012-03-09 17:05:47
@ yes123 - 包含在偏移测试中:http://jsfiddle.net/MhLVV/ – 2012-03-09 17:08:23
我只是先看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的真正魅力在于它经过了严格的测试和打击,你可能不会发现任何问题。除了伟大的选择器引擎和抽象之外,这是值得的。不要害怕真正看。你会在这个过程中学到一些好的副作用。
为什么你打扰,如果你有jQuery的? – dynamic 2012-03-09 16:56:31
'知名度:隐藏;'不是等式的一部分?不知道一个等价物,但这是一个简短的函数。 - @ yes123有时你需要一个函数而不是所有的核心框架作为开销。 – Smamatti 2012-03-09 16:57:42
[这里](https://github.com/jquery/jquery/blob/master/src/css.js#L380)jQuery检查元素是否通过选择器。 – pimvdb 2012-03-09 17:00:20