Javascript-форум (https://javascript.ru/forum/)
-   jQuery (https://javascript.ru/forum/jquery/)
-   -   Точно определить блок при наведении (https://javascript.ru/forum/jquery/66177-tochno-opredelit-blok-pri-navedenii.html)

Vanguger 29.11.2016 16:14

Точно определить блок при наведении
 
Имеется:
<div>
  <div>
    <div>
      <div></div>
    </div>
  </div>
</div>


Подскажите пожалуйста, как при наведении изменить класс блока который под курсором, у меня же получается, что при наведении на дочерний, изменяются все родители:

jQuery('div').hover(function(){
	jQuery(this).addClass('hoverBlock');
}, function(){
	jQuery(this).removeClass('hoverBlock');
});

Pavel M. 29.11.2016 17:07

здесь можно почитать
https://learn.javascript.ru/event-bubbling

Rise 30.11.2016 06:54

Vanguger,
jQuery('div').hover(function(e){
	jQuery(e.target).addClass('hoverBlock');
}, function(e){
	jQuery(e.target).removeClass('hoverBlock');
});

Pavel M. 30.11.2016 11:22

вроде и 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>

Rise 30.11.2016 12:46

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.