admin管理员组文章数量:1241085
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
5 Answers
Reset to default 5myDiv.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.
本文标签: How to detect mousein and mouseleave in pure JavaScriptStack Overflow
版权声明:本文标题:How to detect mousein and mouseleave in pure JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740074245a2223207.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论