【问题标题】:How to implement jQuery .on() function using plain Javascript and document query selectors如何使用纯 javascript 和文档查询选择器实现 jquery .on() 函数
【发布时间】:2016-06-04 08:27:28
【问题描述】:

jquery on() function 允许 DOM 事件在将来可能插入的元素上触发。如何使用纯 javascript 特别是 mouseenter 事件来实现这一点

【问题讨论】:

  • 我认为 jQuery 源代码会对你有所帮助。看那里,用纯 javascript 编写的 jQuery
  • 检查DOMEvents,更具体地说是DOMSubtreeModified。
  • 在网络搜索中不难找到"javascript 事件委托"
  • @charlietfl 当您只想要一个点击事件时,这很容易做到。但是如何实现 mouseenter 呢?
  • @Nevershowmyface 在 DOM 子树中专门寻找鼠标进入事件

标签: javascript jquery html javascript-events mouseevent


【解决方案1】:

在这里找到答案https://developer.mozilla.org/en-US/docs/Web/Events/mouseenter

对于任何有兴趣实现代码的人如下:

<ul id="test">
  <li>
    <ul class="enter-sensitive">
      <li>item 1-1</li>
      <li>item 1-2</li>
    </ul>
  </li>
  <li>
    <ul class="enter-sensitive">
      <li>item 2-1</li>
      <li>item 2-2</li>
    </ul>
  </li>
</ul>

<script>
  var delegationSelector = ".enter-sensitive";

  document.getElementById("test").addEventListener("mouseover", function( event ) {
    var target = event.target,
        related = event.relatedTarget,
        match;

    // search for a parent node matching the delegation selector
    while ( target && target != document && !( match = matches( target, delegationSelector ) ) ) {
        target = target.parentNode;
    }

    // exit if no matching node has been found
    if ( !match ) { return; }

    // loop through the parent of the related target to make sure that it's not a child of the target
    while ( related && related != target && related != document ) {
        related = related.parentNode;
    }

    // exit if this is the case
    if ( related == target ) { return; }

    // the "delegated mouseenter" handler can now be executed
    // change the color of the text
    target.style.color = "orange";
    // reset the color after a small amount of time
    setTimeout(function() {
        target.style.color = "";
    }, 500);


  }, false);


  // function used to check if a DOM element matches a given selector
  // the following code can be replaced by this IE8 compatible function: https://gist.github.com/2851541
  function matches( elem, selector ){
    // the matchesSelector is prefixed in most (if not all) browsers
    return elem.matchesSelector( selector );
  };
</script>

【讨论】:

  • Ya IE 根本不支持closest(),所以你必须为matches() 使用polyfill 并遍历父节点。
猜你喜欢
  • 1970-01-01
  • 2021-12-21
  • 1970-01-01
  • 2013-12-15
  • 2014-09-11
  • 1970-01-01
  • 1970-01-01
  • 2019-01-22
  • 1970-01-01
相关资源
最近更新 更多