如何添加悬停事件侦听器以触发事件侦听器

时间:2021-02-01 20:23:12

I am trying to add a hover event listener to the code below so that when I hover over the link tag, it triggers the action to expand the submenu. I tried hover and mouseover and neither worked. Click seems to work fine though, Im not sure what I am doing wrong.

我正在尝试向下面的代码添加一个悬停事件监听器,这样当我将鼠标悬停在链接标记上时,它会触发扩展子菜单的操作。我试过悬停和鼠标悬停,但都没有奏效。点击似乎工作正常,我不知道我做错了什么。

Array.prototype.slice.call( this.menuItems ).forEach( function( el, i ) {
    var trigger = el.querySelector( 'a' );
    if( self.touch ) {
    ``trigger``.addEventListener( 'touchstart', function( ev ) { 
        self._openMenu( this, ev ); } );
    }
    else {
        trigger.addEventListener( 'click', function( ev ) { self._openMenu( this, ev ); });
    }
});

window.addEventListener('resize', function( ev ) { 
    self._resizeHandler(); 
});

2 个解决方案

#1


1  

Don't punish yourself like this. Use a library like jQuery to attach eventhandlers to elements. Mouseover and hover are both supported by jQuery. Don't reinvent the wheel and build upon existing solutions like bootstrap to implement basic functionality like expanding a submenu.

不要这样惩罚自己。使用像jQuery这样的库将事件处理程序附加到元素。 jQuery支持鼠标悬停和悬停。不要重新发明*并在现有解决方案(如引导程序)的基础上实现扩展子菜单等基本功能。

#2


1  

trigger.addEventListener('click', function(ev) {
   self._openMenu(this, ev);
});

                    Write

trigger.addEventListener('mouseover', function(ev) {
   self._openMenu(this, ev);
});

Replace click event by mouseover event

通过鼠标悬停事件替换单击事件

#1


1  

Don't punish yourself like this. Use a library like jQuery to attach eventhandlers to elements. Mouseover and hover are both supported by jQuery. Don't reinvent the wheel and build upon existing solutions like bootstrap to implement basic functionality like expanding a submenu.

不要这样惩罚自己。使用像jQuery这样的库将事件处理程序附加到元素。 jQuery支持鼠标悬停和悬停。不要重新发明*并在现有解决方案(如引导程序)的基础上实现扩展子菜单等基本功能。

#2


1  

trigger.addEventListener('click', function(ev) {
   self._openMenu(this, ev);
});

                    Write

trigger.addEventListener('mouseover', function(ev) {
   self._openMenu(this, ev);
});

Replace click event by mouseover event

通过鼠标悬停事件替换单击事件