Element.closest()
方法用来获取匹配特定选择器且离当前元素最近的祖先元素(也可以是当前元素本身)。如果匹配不到,则返回 null
。
const result = ele.closest(selector)
请注意,IE 不支持 closest 方法。
const matches = function (ele, selector) {
return (
ele.matches ||
ele.matchesSelector ||
ele.msMatchesSelector ||
ele.mozMatchesSelector ||
ele.webkitMatchesSelector ||
ele.oMatchesSelector
).call(ele, selector)
}
// 找到最接近 `ele` 的元素并匹配 `selector`
const closest = function (ele, selector) {
let e = ele
while (e) {
if (matches(e, selector)) {
break
}
e = e.parentNode
}
return e
}