简体   繁体   中英

hover over a tag class change image src of img in different element

Say I have something like this:

<div class="right">
<article class="left_image">
<img src="images/coolestimageontheplanet.jpg" class="image_left">
</article>

And then I have a UL list:

    <ul class="LISTS">
      <li><a href="#link" target="_blank" class="hov5">Link 1</a></li>
       <!-- etc -->
    </ul>

I would have about 10 list items in the directly above mark-up fashion. Based on hover class I would like to swap out the image source associated with class="image_left" as seen above. So hover over class="hov5" you get the hov5 image .

You could add event listeners for mouseover & mouseleave and then change the image.src accordingly, like in such a way

 window.addEventListener('load', function() { function initImageHover(selector, displaySelector) { var imageContainer = document.querySelectorAll(displaySelector)[0], elements = document.querySelectorAll(selector); for (var i = 0, len = elements.length; i < len; i++) { createHover(elements[i], imageContainer, imageContainer.src); }; } function createHover(that, targetElement, originalImage) { that.addEventListener('mouseover', function() { var src = that.getAttribute('data-src'); if (src) { targetElement.src = src; } }); that.addEventListener('mouseleave', function() { targetElement.src = originalImage; }); } initImageHover('li > a', '.image_left'); }); 
 <div class="right"> <article class="left_image"> <img src="images/coolestimageontheplanet.jpg" class="image_left"> </article> <ul class="LISTS"> <li><a href="#link" target="_blank" class="hov1">Link 1</a> </li> <li><a href="#link" target="_blank" class="hov2">Link 2</a> </li> <li><a href="#link" target="_blank" class="hov3">Link 3</a> </li> <li><a href="#link" target="_blank" class="hov4">Link 4</a> </li> <li><a href="#link" target="_blank" class="hov5">Link 5</a> </li> <li><a href="#link" target="_blank" class="hov6">Link 6</a> </li> <li><a href="#link" target="_blank" data-src="http://cdn.sstatic.net/stackoverflow/img/sprites.svg?v=a7723f5f7e59" class="hov7">Link 7</a> </li> </ul> 

Add a data tag like so:

<ul class="LISTS">
      <li><a href="#link" target="_blank" class="hov5" data-img="images/newimg.jpg">Link 1</a></li>
       <!-- etc -->

Then use a code like this:

$("ul.LISTS>li").hover(function(){
     var imgurl = $(this).data("img");
     $(".image_left").attr("src",imgurl);
},
function(){ 
     $(".image_left").attr("src","images/coolestimageontheplanet.jpg");
});

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