原生JavaScript实现mouseenter

mouseenter和Mouseleave都是jquery的事件,JavaScript的mouseover和mouseout每个子元素都会触发,从子元素移到父元素也会触发,用起来不很方便,而且触发的太多次不必要。

Event.relatedTarget是移动到或从哪里移动来的那个元素,可以判断这个relatedTarget如果既不是currentTarget也不是currentTarget的子元素,就可以判断当前鼠标是从外面移进来或移动到外面去。

// 鼠标悬浮显示控件,类似mouseenter
                var show_controls=function(e){
                    if(e.relatedTarget!==e.currentTarget && e.currentTarget.getElementsByClassName(e.relatedTarget.className).length===0){
                        controls.style.opacity=1;
                        clearTimeout(timeout);
                    }
                    
                    
                };
                var hide_controls=function(e){
                        // console.log(this);
                    if(e.relatedTarget!==e.currentTarget && e.currentTarget.getElementsByClassName(e.relatedTarget.className).length===0){
                        timeout=setTimeout(hide,500);
                    }
                    function hide(){
                        // console.log("timeout",this);
                        controls.style.opacity=0;
                    }

                
                }

不知道怎么判断是不是子元素,我的一块里子元素的类名并不重复,就用了类名查找,结果长度大于0就是子元素。。。。好麻烦好别扭的样子。。回头研究研究。

原文地址:https://www.cnblogs.com/zqiong/p/5265977.html