Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

jquery - Hover on text link to change image

I'm working on a project and need to work out some simple jQuery for a text rollover that changes the image in the div behind it.

See the idea here - http://sharifabraham.com/projects/

I would like the image to fade in on:hover and fade out when the mouse leaves. Each link on the nav will show the first image of the project.

Make sense?

Is this possible with CSS even?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is just an outline of what you could do. On hover, we create a new img that will hold the necessary image and append it to #slider. The new img needs absolute positioning to appear on top of the previous image (we need this for fading). When mouse leaves the link, we just remove the img.

Change your HTML like this (add the corresponding image's URL to a data- attribute):

<a class="hoverlink" data-img="../images/flinders_house.jpg" href="...

And some jQuery:

var $slider=$('#slider'); //we save the slider
var $defaultimage=$('img', $slider); //and the default image

//mouseenter for the link
$('#projects .hoverlink').hover(function () { 
  var filename=$(this).attr('data-img'); //we get the filename from data-img

  $('<img id="hoverimage" src="'+filename+'" alt="" />')
    .appendTo($slider).fadeIn(500); //append and fade in new image (#hoverimage)

  $defaultimage.fadeOut(500); //fade out default image
}, 
//mouseleave for the link
function () { 
  $('#hoverimage').fadeOut(500, function () { //fade out #hoverimage
    $(this).remove(); //when animation is done, remove it
  });

  $defaultimage.fadeIn(500); //meanwhile fade in original image
});

Also we need some CSS changes:

/* #hoverimage needs to appear on top of default image */
#slider { position: relative; }
#hoverimage { position: absolute; top: 0; left: 0; z-index: 100; }

NOTE: I haven't taken into consideration the loading time for these quite big images, my code assumes they are already cached. You could either do some preloading, or only start the fading effects when the image has loaded (.load()). The latter is not reliable in Opera if I remember well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...