Точно определить блок при наведении
Имеется:
<div> <div> <div> <div></div> </div> </div> </div> Подскажите пожалуйста, как при наведении изменить класс блока который под курсором, у меня же получается, что при наведении на дочерний, изменяются все родители: jQuery('div').hover(function(){ jQuery(this).addClass('hoverBlock'); }, function(){ jQuery(this).removeClass('hoverBlock'); }); |
здесь можно почитать
https://learn.javascript.ru/event-bubbling |
Vanguger,
jQuery('div').hover(function(e){ jQuery(e.target).addClass('hoverBlock'); }, function(e){ jQuery(e.target).removeClass('hoverBlock'); }); |
вроде и jQuery(this).addClass('hoverBlock');
работает? <!DOCTYPE html> <html> <head> <title>test</title> <script src="https://code.jquery.com/jquery-3.1.0.js"></script> <style> div { padding: 20px; border: 1px solid; background-color: white; } .hoverBlock { background-color: red; } </style> <head> <body> <div> <div> <div> <div></div> </div> </div> </div> <script> jQuery('div').hover(function(e){ jQuery(this).addClass('hoverBlock'); }, function(e){ jQuery(this).removeClass('hoverBlock'); }); </script> </body> </html> |
Pavel M., всё верно) hover использует mouseenter/mouseleave которые не всплывают, тогда сделаем так:
<div> <div> <div> <div></div> </div> </div> </div> <script> $('div').mouseover(function(e) { e.stopPropagation(); $(e.target).addClass('hoverBlock'); }).mouseout(function(e) { e.stopPropagation(); $(e.target).removeClass('hoverBlock'); }); </script> <!----- или -----> <div class="ddd"> <div> <div> <div></div> </div> </div> </div> <script> $('div.ddd').mouseover(function(e) { $(e.target).addClass('hoverBlock'); }).mouseout(function(e) { $(e.target).removeClass('hoverBlock'); }); </script> |
Часовой пояс GMT +3, время: 04:06. |