[英]Event delegation, Event.target vs Event.currentTarget
在MDN Event.target 参考中有一个关于实现事件委托的例子:
// Assuming there is a 'list' variable containing an instance of an
// HTML ul element.
function hide(e) {
// Unless list items are separated by a margin, e.target should be
// different than e.currentTarget
e.target.style.visibility = 'hidden';
}
list.addEventListener('click', hide, false);
// If some element (<li> element or a link within an <li> element for
// instance) is clicked, it will disappear.
// It only requires a single listener to do that
我在这个例子中不明白的是这个评论:
// Unless list items are separated by a margin, e.target should be
// different than e.currentTarget
<li>
元素的边距如何在Event.target
和Event.currentTarget
之间产生差异?
请记住是什么使event.target
与event.currentTarget
不同,如MDN Event.currentTarget 参考中所述:
我认为关键是如果没有边距,则无法直接单击ul
因为li
元素将完全填满其空间。
如果有余量,那么它至少会是可能的点击ul
,在这种情况下event.target
和event.currentTarget
将是相同的。
function hide(e) { document.querySelector("pre").textContent += 'e.target = ' + e.target.nodeName + ", e.currentTarget = " + e.currentTarget.nodeName + "\\n"; } document.querySelector("#list").addEventListener('click', hide, false);
ul { border: 2px solid orange; } li { padding: 10px; color: blue; margin: 30px; border: 1px dashed blue; }
<pre></pre> <ul id="list"> <li>click me <li>click me <li>click me </ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.