我想知道是否支持方法closest (),如果需要(IE 11),请使用以下形式的替代方法:
ancestor = ('closest' in document.documentElement) ? element.closest (selector) : element.parentElement;我的浏览器(Edge、Chrome、Firefox、IE 11 - WIN 10)的控制台根据预期返回'true‘或'false’。
这个解决方案是干净的解决方案,还是有我没有考虑到的陷阱?
发布于 2019-08-19 02:52:56
最好使用polyfill来检查方法是否存在,如果不存在,则将其添加到对象原型中。然后在所有浏览器中使用该方法。
https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill
发布于 2019-08-19 02:53:19
Lets see what MDN says about this:
对于不支持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;
do {
if (el.matches(s)) return el;
el = el.parentElement || el.parentNode;
} while (el !== null && el.nodeType === 1);
return null;
};
}所以你的方法是正确的。请使用consult mdn for further info
https://stackoverflow.com/questions/57547432
复制相似问题