问题
i found this script to change images on hover.
$(document).ready(function() {
$('.rollover').hover(function() {
swapImage(this);
}, function() {
swapImage(this);
});
});
function swapImage(image) {
var current = $(image).attr('src');
$(image).attr('src', $(image).attr('hover'));
$(image).attr('hover', current);
}
But now i'm having the problem, that i want a smooth/soft transit and not that, what it does now. Here you can find a fiddle: JSfiddle
Thanks and a nice sunday!
回答1:
It is swapping very smoothly for me. Your swapping method is probably going to depend a lot on the browser, OS, and hardware specs of the user's computer, as you're doing a lot of work in changing the image src
via JS.
While browsers are usually intelligent enough to keep previously-loaded images cached and easily reachable, your method won't always be smooth on that first transition because the browser doesn't know about the new image until you change src
, at which point the browser starts downloading the image. Unfortunately, you're also trying to show the image at this point, so there will be some disconnect while the image is shown but not actually loaded.
An easier way would be to have both images already loaded onto the page (so have two <img>
tags), and hide one. Then on rollover, swap which one is hidden and which is shown, and swap back when not hovering. This swapping effect can be achieved purely in CSS, which will be faster than JS. It will also pre-load the hidden images before user interaction since the second image is already on the page, so that you can immediately start with a smoother transition to the hidden image.
I've modified your fiddle with the below code. I added a class to <a>
, and added a second <img>
instead of using the hover
attr. A couple of HTML notes: hover
is an invalid attribute on <img>
(or any other element for that matter). You should use data-hover
instead, if anything, which follows the standard HTML5 data-*
custom attribute spec, but we won't need it for this CSS solution. Also, you were missing a closing </div>
tag in your fiddle.
HTML:
<div class="col-1">
<a class="rollover-container" rel="img_gal" href="gal/m.jpg">
<img class="rollover" src="http://schanzenstrasse.de/gal/c1_sw.jpg"/>
<img class="rollover-swap" src="http://schanzenstrasse.de/gal/c1.jpg"/>
</a>
</div>
CSS:
.rollover-swap {
display: none; /*Hide the rollover image*/
}
.rollover-container:hover .rollover {
display: none; /*If we hover over the <a>, then hide the normal image*/
}
.rollover-container:hover .rollover-swap {
display: inline; /*If we hover over the <a>, then show the rollover image*/
}
JS:
None!
来源:https://stackoverflow.com/questions/19891138/how-to-keep-imageswap-smooth-jquery