简体   繁体   中英

How to hover two elements implicitly while hovering another one with JQuery?

is there a way to trigger the hover of two elements when hovering on another one with JQuery?

Here is my HTML:

<!DOCTYPE HTML>
   <html lang="">
    <head>
      <meta http-equiv="Content-Type" content="text/html"/>
      <meta charset="utf-8"/>
          <script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
          <script type='text/javascript' src='javascript.js'></script>
          <link rel='stylesheet' href='style.css' type='text/css'>
      <title>Title</title>
   </head>
   <body>
       <div class='hidden'></div>
       <div class='triggerOtherHover' onmouseover='hoverImplicitly();'></div>
       <div class='hidden'></div>
   </body>
  </html> 

Here is my style.css:

.hidden { 
          background-color:red;
          border: 1px solid black;
          opacity:0;
          transition: opacity 0.4s ease-in-out;
          width: 100px;
          height:100px;
 }
.hidden:hover, .visible {
          opacity:1;
}

.triggerOtherHover {
           width:100px;
           height:100px;
           background-color:green;
}

Here is my javascript.js:

function hoverImplicitly {
           $(".hidden").toggleClass('visible');
}

When I hover the mouse on the div.triggerOtherHover , the other two divs with .hidden class become red cause of the opacity, but when I remove the mouse from the div.triggeOtherHover, the divs are still red. I would like them to become transparent (opacity: 0) again. Is there a way to make them behave like the CSS :hover pseudo class?

You need to add a mouseout handler to the div as well, so that the class gets removed when focused out of it.

   <div class="triggerOtherHover" onmouseover="hoverImplicitly();" onmouseout="hoverImplicitly();">

Or instead of adding inline handler bind the event to the element using hover pseudoevent.

 $(function(){
    $('.triggerOtherHover').hover(hoverImplicitly); //hover represent mouseenter, mouseleave
});

Also note that you are missing parens () in the function declaration function hoverImplicitly()

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