Simulate hover using JavaScript events

前端 未结 4 1798
渐次进展
渐次进展 2021-01-05 22:26

Is it possible to simulate hover using JavaScript Events? I tried injecting mouseover event on the target element but no luck.

For example, if there is a link that

4条回答
  •  孤街浪徒
    2021-01-05 23:20

    Actually, CSS hover event is more convenient than just binding these two events mouseenter and mouseleave. So it'll need a little more efforts, which are:

    1.Clone the element

    2.Add a listener to mouseenter event

    3.Recursively redo step 1,2 and restore the cloned element on mouseleave

    Here is my working draft.

    function bindHoverEvent(element,listener){
        var originalElement = element.cloneNode(true);
        element.addEventListener('mouseenter',listener);
        element.addEventListener('mouseleave',function(){
            bindHoverEvent(originalElement,listener);
            this.parentNode.replaceChild(originalElement,this);
        });
    }
    

    Please note that, cloneNode does not copy event listeners, so you need to manually rebind events to the cloned element and all its children yourself.

提交回复
热议问题