嵌套元素的mouseover和mouseout事件 mouseovermouseoutjquery
程序员文章站
2022-07-12 21:34:24
...
今天在帮别人解决一个关于mouseover和mouseout问题的时候发现了一个原来没想到的问题,斗胆share下,高手莫喷。。
问题:有嵌套的三层div。div111最外层,div222中间层,div333最内层。
效果:当鼠标位于div的上方时,相应层的mouseover触发,当属性从div的上方离开时,相应层的mouseout触发。
此段代码同时也解决了mouseover和mouseout由于子元素的冒泡而产生的一些问题。不知道有没更好的方案?
问题:有嵌套的三层div。div111最外层,div222中间层,div333最内层。
效果:当鼠标位于div的上方时,相应层的mouseover触发,当属性从div的上方离开时,相应层的mouseout触发。
此段代码同时也解决了mouseover和mouseout由于子元素的冒泡而产生的一些问题。不知道有没更好的方案?
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>test</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <style> #div111{ width:200px; height :200px ; background :red; margin :100px auto auto 100px; border: 2px solid white; } #div222{ width:100px; height :100px; background :yellow; border: 2px solid white; } #div333{ width:50px; height :50px; background :blue; border: 2px solid white; } </style> </head> <body> <div id="div111"> <div id="div222"> <div id="div333"></div> </div> </div> <div id="log"></div> <script type ="text/javascript" > function mouse_over(event){ var elem = $(event.currentTarget), fromElem = $(event.relatedTarget); if(elem.has(fromElem).length === 0 || !fromElem.is(elem)){ elem.css('border-color', 'green'); log(elem.attr('id'), event.type); } }; function mouse_out(event){ var elem = $(event.currentTarget), toElem = $(event.relatedTarget); if(elem.has(toElem).length === 0 || !toElem.is(elem)){ elem.css('border-color', 'white'); log(elem.attr('id'), event.type); } }; function log(id, type){ $("#log").append("<div><span>" + id + "触发了<strong><font color='red'>" + type + "</font></strong>事件</span></div>"); } $('#div111').mouseover(mouse_over); $('#div222').mouseover(mouse_over); $('#div333').mouseover(mouse_over); $('#div111').mouseout(mouse_out); $('#div222').mouseout(mouse_out); $('#div333').mouseout(mouse_out); </script> </body> </html>
推荐阅读
-
嵌套元素的mouseover和mouseout事件 mouseovermouseoutjquery
-
jQuery嵌套元素的mouseover和mouseout事件详解
-
经过绑定元素时会多次触发mouseover和mouseout事件_javascript技巧
-
鼠标经过子元素触发mouseout,mouseover事件的解决方案_javascript技巧
-
经过绑定元素时会多次触发mouseover和mouseout事件_javascript技巧
-
jQuery事件mouseover和mouseout在鼠标经过子元素时也会触发详解
-
鼠标经过子元素触发mouseout,mouseover事件的解决方案_javascript技巧
-
jQuery事件中mouseout和mouseover有子元素的情况