js事件委托,某些子元素不触发事件改如何处理呢?

js事件委托,某些子元素不触发事件改如何处理呢?

如:


<ul>

    <li>

        <a>11111</a>

    </li>

    <li>

        <a>11111</a>

    </li>

    <li>

        <a>11111</a>

    </li>

    <li>

        <a>11111</a>

    </li>

    <li>

        <a>11111</a>

    </li>

</ul>

我想当鼠标移动到后面5个li中时,事件才执行。仅仅移动到ul,或者第1个<li><a>11111</a></li>时不执行。


我该怎么做呢。


我为ul绑定‘mouseenter’时,它只会在移动到ul范围执行。

绑定‘mousemove’时,我给ul和不需要执行事件的li都个notRun的属性,有这个属性时它就不执行事件。但是li中的所有子元素还是会触发事件,难道我还要把li的子元素也加上notRun属性吗?


我应该怎么做才更合理呢?


繁星淼淼
浏览 384回答 1
1回答

九州编程

你移入li时e.target是li,在文字上是e.target是a了,给a一个穿透的css,这样移入的全是li了,或者你判断e.target是a的话,则是e.target.parentNode的getAttribute("notRun"),否者就是e.target的getAttribute("notRun")<!DOCTYPE html><html><head>&nbsp; &nbsp; <meta charset="UTF-8">&nbsp; &nbsp; <meta name="viewport" content="width=device-width, initial-scale=1.0">&nbsp; &nbsp; <meta http-equiv="X-UA-Compatible" content="ie=edge">&nbsp; &nbsp; <title>Document</title>&nbsp; &nbsp; <style>&nbsp; &nbsp; &nbsp; &nbsp; li a{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pointer-events: none;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </style></head><body>&nbsp; &nbsp; <ul>&nbsp; &nbsp; &nbsp; &nbsp; <li notRun="true">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a>11111</a>&nbsp; &nbsp; &nbsp; &nbsp; </li>&nbsp; &nbsp; &nbsp; &nbsp; <li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a>11111</a>&nbsp; &nbsp; &nbsp; &nbsp; </li>&nbsp; &nbsp; &nbsp; &nbsp; <li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a>11111</a>&nbsp; &nbsp; &nbsp; &nbsp; </li>&nbsp; &nbsp; &nbsp; &nbsp; <li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a>11111</a>&nbsp; &nbsp; &nbsp; &nbsp; </li>&nbsp; &nbsp; &nbsp; &nbsp; <li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a>11111</a>&nbsp; &nbsp; &nbsp; &nbsp; </li>&nbsp; &nbsp; </ul>&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; &nbsp; var ul = document.querySelector('ul');&nbsp; &nbsp; &nbsp; &nbsp; ul.addEventListener('mouseover',function(e){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if((!e.target.getAttribute("notRun"))&&e.target.tagName==="LI"){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(111);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; </script></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript