多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[toc] ![](https://box.kancloud.cn/7454c4f2bc597df1ca6436449bed9bfc_898x323.png) JQ版 ``` //->等价于$(document).ready() 当页面上的HTML结构都加载完成后执行对应的函数 $(function(){ var $box = $('#box'),$mark = $('#mark'); var $boxOffset = $box.offset(); //->获取当前元素距离body的偏移{top:xxx,left:yyy} $box.children("img").bind("mouseover",function(e){ e = e || window.event; e = e.target || e.srcElement; var left = e.clientX - $boxOffset.left +10; var top = e.clientY - $boxOffset.top + 10; //->hide、toggle、slideDown、slideUp、slideToggle、fadeIn、fadeOut、fadeToggle、animate... $mark.show(500).css({left:left,top:top}).find("img").attr("src",e.target.getAttribute("bigImg"));//children是只找子 find是找所有后代 }) ....; // $box.children("img").on("mouseover") // $box.children("img").mouseover(function(){}) }); ``` ## 注意事项 1. 鼠标移动过快的话可能会到mark上(触发mark的mouseover,再冒泡到box的mouseover(也就会再创建一个div)),当mark反应过来跟上的时候,也就会触发mark的mouseout,mark的mouseout会传播到box上,也会触发box的mouseout(删除div),但此时mark已经从鼠标爪子下溜走,mark重新出现在box上,会触发box的mouseover(创建div) (需要阻止mask的传播,还要在第一创建mask后取消box的mouseover对应创建div的事件) 2. 鼠标如果过快跑到mark上,但没有跑出box,也不会触发mouseout,下面这个例子可以确定 ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #father{ width: 400px; height: 400px; border:1px solid black; } #son{ width: 50px; height: 50px; background:rebeccapurple; position: absolute; } </style> </head> <body> <div id="father"> <div id="son"></div> </div> <script> father.addEventListener('mouseover',function(e){ console.log(1); }) father.addEventListener('mouseout',function(e){ console.log(2); }) father.addEventListener('mousemove',function(e){ son.style.left = e.clientX+'px'; son.style.top = e.clientY+'px'; }) </script> </body> </html> ``` ## onmouseenter 兼容性:ie7没问题 onmouseenter和onmouseover都是鼠标滑上去的行为,但是onmouseenter浏览器默认阻止了它的冒泡传播;而onmouseover是存在冒泡传播的,想要阻止要自己写代码 ## 鼠标跟随的问题 放大镜和submenu的区别在于,submenu从主容器移动到 mark上会触发mouseout/leavr,而放大镜不会(因为放大镜的mark就在主容器里);并且从mark上移开也会触发主容器的 mouseout/leave(因为冒泡) ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #father{ width: 200px; height: 50px; position: relative; background:pink } #son{ width: 100px; height: 100px; border:1px solid black; position: absolute; top:50px; display: none } #father:hover #son{ display: block } </style> </head> <body> <div id="father"> <div id="son"></div> </div> <script> father.onmouseover = function(){ console.log(1); son.style.display = 'block'; } father.onmouseout = function(){ console.log(2); son.style.display = 'none'; } son.onmouseover = function(){} </script> </body> </html> ```