简体   繁体   中英

Jquery - Change image with anchor text rollover

Im building a menu in Jquery and I need to be able to change the image src when a text link is on mouse over.

I have got as far as building the menu with a basic image rollover, but I need the image to change when the text in the anchor link is on mouseover too. So the image will rollover when the anchor text is on mouse over, as well as when the image itself it...

Here is my code so far:

CSS:

 #subNav {
 list-style: none;
 }
 #subNav li {
 width: 130px;
 float: left;
 text-align:center;
 }
 #subNav li a {
 font-family: 'News Cycle', sans-serif;
 font-size:14px;
 text-decoration:none;
 color: #d33800;
 }
 #subNav li a:hover {
  color:#666666;
  }
 #subNav li a img {
  display: block;
  margin:auto;
  width: 88px;
  }

JQUERY:

  $(document).ready(function () {

//rollover swap images with rel
var img_src = "";
var new_src = "";

$(".overlay").hover(function(){
//mouseover
img_src = $(this).attr('src'); //grab original image
new_src = $(this).attr('rel'); //grab rollover image
$(this).attr('src', new_src); //swap images
$(this).attr('rel', img_src); //swap images
},
function(){
//mouse out
$(this).attr('src', img_src); //swap images
$(this).attr('rel', new_src); //swap images
});

//preload images
var cache = new Array();
//cycle through all rollover elements and add rollover img src to cache array
$(".overlay").each(function(){
   var cacheImage = document.createElement('img');
cacheImage.src = $(this).attr('rel');
cache.push(cacheImage);
});

    });

HTML

<ul id="subNav">
 <li><a href=""><img src="1-orange.png" rel="1-grey.png" class="overlay" alt="Bookings">Bookings</a></li>
 <li><a href=""><img src="2-orange.png" rel="2-grey.png" class="overlay" alt="Accomodation">Accomodation</a></li>
 <li><a href=""><img src="3-orange.png" rel="3-grey.png" class="overlay" alt="Eating">Eating</a></li>
 <li><a href=""><img src="4-orange.png" rel="4-grey.png" class="overlay" alt="Dates &amp; Prices">Dates &amp; Prices</a></li>
 <li><a href=""><img src="5-orange.png" rel="5-grey.png" class="overlay" alt="Travel Options">Travel Options</a></li>
 <li><a href=""><img src="6-orange.png" rel="6-grey.png" class="overlay" alt="Contact">Contact</a></li>
</ul>

Unless you're doing something I'm missing there's no need for jQuery to change images on mouse over.

Have you tried to put the images as backgrounds instead and then change the background via the hover events in CSS?

Do you have any live example with the images so that we better can see what you're trying to accomplish (and help you out better since there are usually many ways to solve a problem).

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