最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to detect mousein and mouseleave in pure JavaScript? - Stack Overflow

programmeradmin3浏览0评论

I can't use jQuery for this part of the project due to various reasons. SO I need to detect this in vanilla js. I tried this but it doesn't work:

/

var myDiv = document.getElementById('foo');

myDiv.onmouseenter = function() { 
    alert('entered');
}

myDiv.onmouseleave = function() { 
    alert('left');
}

I can't use jQuery for this part of the project due to various reasons. SO I need to detect this in vanilla js. I tried this but it doesn't work:

http://jsfiddle/qHfJD/

var myDiv = document.getElementById('foo');

myDiv.onmouseenter = function() { 
    alert('entered');
}

myDiv.onmouseleave = function() { 
    alert('left');
}
Share Improve this question asked Mar 7, 2013 at 19:56 user967451user967451 1
  • This question may help explain the difference between the events. – DOK Commented Mar 7, 2013 at 20:01
Add a ment  | 

5 Answers 5

Reset to default 5
myDiv.onmouseover = function(event) {
  if (this != event.currentTarget) { return false; }
  // mouse enter ...
}
myDiv.onmouseout = function(event) {
  if (this != event.currentTarget) { return false; }
  // mouse leave ...
}

mouseenter and mouseleave are proprietary MS events (that are actually pretty nice). If myDiv has no children, using mouseover / mouseout will have exactly the same effect.

http://jsfiddle/qHfJD/1/

Note: this original question and answer were very old and from a time when mouseenter and mouseleave were not well supported outside of IE. All modern browsers have supported these events on elements for quite some time now. They are generally preferred over mouseover/mouseout because the latter will trigger for each child of the element with the event listener in addition to the element itself.

The mouseenter and mouseleave events are proprietary to Internet Explorer, so if you aren't using IE, they won't work. Use mouseover and mouseout, instead.

By the way, you can use mouseenter and mouseleave via jQuery because jQuery simulates those events for you on non-IE browsers. See this article for tips on how to simulate mouseenter and mouseleave for yourself.

You are close. The function name is onmouseover and onmouseout

var myDiv = document.getElementById('foo');

myDiv.onmouseover = function() { 
  alert('entered');
}

myDiv.onmouseout = function() { 
  alert('left');
}

Try: var myDiv = document.getElementById('foo');

myDiv.onmouseover = function() { 
    alert('entered');
}

myDiv.onmouseout = function() { 
    alert('left');
}

onmouseenter and onmouseleave are IE-only functionality.

发布评论

评论列表(0)

  1. 暂无评论