From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- files/zh-cn/web/api/element/closest/index.html | 142 +++++++++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 files/zh-cn/web/api/element/closest/index.html (limited to 'files/zh-cn/web/api/element/closest/index.html') diff --git a/files/zh-cn/web/api/element/closest/index.html b/files/zh-cn/web/api/element/closest/index.html new file mode 100644 index 0000000000..8e89eb8534 --- /dev/null +++ b/files/zh-cn/web/api/element/closest/index.html @@ -0,0 +1,142 @@ +--- +title: Element.closest() +slug: Web/API/Element/closest +tags: + - API + - DOM + - Element + - Method + - Reference +translation_of: Web/API/Element/closest +--- +
+

{{APIRef('Shadow DOM')}}

+
+ +

Element.closest() 方法用来获取:匹配特定选择器且离当前元素最近的祖先元素(也可以是当前元素本身)。如果匹配不到,则返回 null

+ +

语法

+ +
var closestElement = targetElement.closest(selectors);
+
+ +

参数

+ + + +

返回值

+ + + +

异常

+ + + +

示例

+ +

HTML

+ +
<article>
+  <div id="div-01">Here is div-01
+    <div id="div-02">Here is div-02
+      <div id="div-03">Here is div-03</div>
+    </div>
+  </div>
+</article>
+ +

JavaScript

+ +
var el = document.getElementById('div-03');
+
+var r1 = el.closest("#div-02");
+// 返回 id 为 div-02 的那个元素
+
+var r2 = el.closest("div div");
+// 返回最近的拥有 div 祖先元素的 div 祖先元素,这里的话就是 div-03 元素本身
+
+var r3 = el.closest("article > div");
+// 返回最近的拥有父元素 article 的 div 祖先元素,这里的话就是 div-01
+
+var r4 = el.closest(":not(div)");
+// 返回最近的非 div 的祖先元素,这里的话就是最外层的 article
+ +

兼容

+ +

部分浏览器并不支持Element.closest(),但却支持了element.matches()(或拥有私有前缀,如IE9+),一个polyfill案例:

+ +
if (!Element.prototype.matches)
+    Element.prototype.matches = Element.prototype.msMatchesSelector ||
+                                Element.prototype.webkitMatchesSelector;
+
+if (!Element.prototype.closest)
+    Element.prototype.closest = function(s) {
+        var el = this;
+        if (!document.documentElement.contains(el)) return null;
+        do {
+            if (el.matches(s)) return el;
+            el = el.parentElement;
+        } while (el !== null);
+        return null;
+    };
+ +

然而,如果你需要兼容到IE8,那么随后这个polyfill将会非常缓慢地运行到结束。并且,IE8只支持CSS2.1的选择器,并且使网页运行非常缓慢。

+ +
if (window.Element && !Element.prototype.closest) {
+    Element.prototype.closest =
+    function(s) {
+        var matches = (this.document || this.ownerDocument).querySelectorAll(s),
+            i,
+            el = this;
+        do {
+            i = matches.length;
+            while (--i >= 0 && matches.item(i) !== el) {};
+        } while ((i < 0) && (el = el.parentElement));
+        return el;
+    };
+}
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-element-closest', 'Element.closest()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ +

{{Compat("api.Element.closest")}}

+ +

兼容性说明

+ + + +

相关链接

+ + -- cgit v1.2.3-54-g00ecf