pure javascript to check if something has hover (without setting on mouseover/out)

后端 未结 4 1000
死守一世寂寞
死守一世寂寞 2020-11-29 00:50

I have seen this jQuery syntax:

if($(element).is(\':hover\')) { do something}

Since I am not using jQuery, I am looking for the best way to

4条回答
  •  迷失自我
    2020-11-29 01:28

    You can use querySelector for IE>=8:

    const isHover = e => e.parentElement.querySelector(':hover') === e;    
    
    const myDiv = document.getElementById('mydiv');
    document.addEventListener('mousemove', function checkHover() {
      const hovered = isHover(myDiv);
      if (hovered !== checkHover.hovered) {
        console.log(hovered ? 'hovered' : 'not hovered');
        checkHover.hovered = hovered;
      }
    });
    .whyToCheckMe {position: absolute;left: 100px;top: 50px;}
    HoverMe
    Do I need to be checked too?

    to fallback I think it is ok @Kolink answer.

提交回复
热议问题