简体   繁体   中英

Jquery change image on rollover with fade

I'm currently using the script below to change an image on rollover. There are many images that this effect needs to be applied to - each image has its own rollover image. The script works for the rollover, but not for the fade.

I've read about using CSS and jquery for the fade effect: http://jqueryfordesigners.com/image-cross-fade-transition/

But it would be a real pain having to write the CSS for over 100 different images! I was just wondering if anyone knows what I'm doing wrong and how to make the script work? :)

$(function () {
$("img.rollover").hover(function () {
    this.src = this.src.replace("_off", "_on")
}, function () {
    this.src = this.src.replace("_on", "_off")
})
});


$("a img").hover(function () {
    jQuery(this).stop().fadeTo("fast", 0.5);
}, function () {
    jQuery(this).stop().fadeTo("fast", 1);
});

Instead of writing the CSS for over 100 different images, why not use a jQuery .each loop to add the CSS for you?

$("img.rollover").each(function() {
    this.css('background-image',this.src.replace("_off", "_on"));
});

...and then follow the single-image technique from the page you linked to .

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