简体   繁体   中英

Jquery image rollover on parent li hover

I have a responsive image based nav menu that I previously used jQuery to swap out a rollover image.

<ul id="mainmenu">
  <li><a href="#"><img src="nav1-off.png" class="rollover"/></a>
      <div class="mega-menu"><p>Mega menu content in here</p></div>
  </li>   
  <li><a href="#"><img src="nav2-off.png" class="rollover"/></a>
      <div class="mega-menu"><p>Mega menu content in here</p></div>
  </li>
</ul> 

$("img.rollover").hover(
            function() { this.src = this.src.replace("-off", "-on");
            },
            function() { this.src = this.src.replace("-on", "-off");
            });

How do I instead toggle the image src when its parent li is hovered over.

Basically I need to do this so that when the newly added mega menu divs are hovered over the hover image still shows in the menu. Tried this but no luck -

$("img.rollover").parent().hover(
    function() {
    $("img.rollover",this).src = $("img.rollover",this).attr("src").replace("-off", "-on");
    },
    function() {
    $("img.rollover",this).src = $("img.rollover",this).attr("src").replace("-on", "-off");
    });
$("#mainmenu").on("mouseenter", "li", function(){
    var rollover = $(this).find(".rollover")[0];
    rollover.src = rollover.src.replace("-off", "-on");
}).on("mouseleave", "li", function(){
    var rollover = $(this).find(".rollover")[0];
    rollover.src = rollover.src.replace("-on", "-off");
});

Example: http://jsfiddle.net/n5RCV/

If you are willing to refactor your html a bit, this problem would probably be better handled with css. You would get better performance, and (arguably) would have easier maintenance of the images. Here is a mockup for css usage. I just mashed it up, so you may have to refine a bit...

<ul id="mainmenu">
  <li id="nav1" ><span class="nav-img"></span>
      <div class="mega-menu"><p>Mega menu content in here</p></div>
  </li>   
  <li id="nav2" ><span class="nav-img"></span>
      <div class="mega-menu"><p>Mega menu content in here</p></div>
  </li>

</ul>

<style>

    /* default settings for all nav image spans */
     #mainmenu > li > .nav-img {
        display: inline-block;
        background-image: url("nav-default.png") no-repeat;

        /* can override dimensions in #nav specific tags */
        width: 50px;
        height: 50px;


     }

     #nav1 > .nav-img{ background-image: url("nav1-off.png") no-repeat; width:100px; height: 100px }
     #nav1:hover > .nav-img{ background-image: url("nav1-on.png") no-repeat; }

     #nav2 > .nav-img{ background-image: url("nav2-off.png") no-repeat; }
     #nav2:hover >  .nav-img{ background-image: url("nav2-on.png") no-repeat; }


</style>

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