简体   繁体   中英

Trigger a hover effect while hovering on another div

At the moment, I am learning how to write in javascript and jquery.I wrote a simple jquery code where when you hover one div, a second div will be hovered too. However, the code I wrote is not working. My knowledge is not enough to fix the mistake I made by myself that's why if someone can help me I am going to be really grateful.

PS: I know that it can be done only with CSS but I am not interested in that.

My code:

 $('.Box1').mouseover(function(e) { $('.Box2').trigger(e.type); }) 
 body{ margin:0; padding:0; background-color:green; } .Box1{ position:relative; width:100vw; height:10vh; transition: background-color 1s ease; } .Box1:hover{ background-color:#FFF; } .Box2{ position:absolute; top:10vh; width:100vw; height:20vw; background-color:red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="Box1"></div> <div class="Box2"></div> 

You'll just have to "fake" a hover event. Take any code that you would have attached to the .Box2:hover css and assign it to a class. When you hover over .Box1, add the class to .Box2, when you hover off, remove the class. The code would look like the following:

Working Demo

CSS

.Box2{
  position:absolute;
  top:10vh;
  width:100vw;
  height:20vw;
  background-color:red;
  transition: background-color 1s ease;
}

.Box2:hover, .Box2.hovered {
  background-color: #FFF;
}

jQuery

$(function () {
  $('.Box1').mouseover(function(e) {
    $('.Box2').addClass("hovered");
  });
  $(".Box1").mouseout(function () {
    $(".Box2").removeClass("hovered");
  });

  // or optionally using .hover() for in/out handling as per A. Wolff's comment
  $(".Box1").hover(function () {
    $(".Box2").addClass("hovered");
  }, function () {
    $(".Box2").removeClass("hovered");
  });
});

Your code does trigger the mouseover event for Box2 - you can test this by adding a handler:

$('.Box2').mouseover(function() {console.log('hello')})

However, this does not activate the css :hover property of Box2 (if it were defined). You will probably need to write a handler for Box2's mouseover event that manipulates the css properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM