Ran*_*all 4 javascript events match
不关心旧浏览器回退。此外,不能使用库。
我有一个事件对象。我正在通过matchesSelector针对css选择器测试event.target:
event['target'].matchesSelector('css selector here');
这有效,就像:
event['target']['parentElement'].matchesSelector('css selector here');
...和:
event['target']['parentElement']['parentElement'].matchesSelector('css selector here');
我正在寻找的是一些超出我理解的可能的对象方法,我可以用它来检查每个 parentElement 一直到匹配,没有for
循环。我的重点是效率。
谢谢!
在最近的()函数会做你的需要。
它从元素本身开始,遍历父元素(朝向文档根),直到找到与提供的 selectorString 匹配的节点。有点类似于jQuery的parents()
功能。
所以你的代码看起来像这样:
event.target.closest(selectorString)
Run Code Online (Sandbox Code Playgroud)
为了防止对目标元素的所有父元素进行冗余循环,您可以使用 with 选择器快速检查您的元素是否位于与选择器匹配的元素内部,该选择器matchesSelector()
是原始选择器和附加上下文选择器(由空格和空格组成)的串联。你的目标元素的标签名称:
function getAncestorBySelector(elem, selector) {
if (!elem.matchesSelector(selector + ' ' + elem.tagName)) {
// If element is not inside needed element, returning immediately.
return null;
}
// Loop for finding an ancestor element that matches your selector.
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4677 次 |
最近记录: |