简体   繁体   中英

jquery change image src on rollover

I have a two images and their rollover images. Using jQuery, I want to show/hide the rollover image when the onmousemove/onmouseout event happen. All my image names follow the same pattern, like this:

Original Image: /CompleteEducation/images/icons/toggleIcon.png

Rollover Image: /CompleteEducation/images/icons/toggleIconDisabled.png

I have used following code but this code overwrite the name:

$(function() {
    $("img")
        .mouseover(function() { 
            var src = $(this).attr("src").match(/[^\.]+/) + "toggleIconDisabled.png";
            $(this).attr("src", src);
        })
});

How can I do it using jQuery?

You say on each mouseover, check if the current images' attribute SRC contains the file name you like. And if yes, then you change the source. You can though replace my sample strings if they are wrong.

My Html:

<img src='http://velocityagency.com/wp-content/uploads/2013/08/go.jpg' width='500' >

My JS:

// make sure you have put your code inside the Document.ready
$(document).ready(function(){

    $("img").on("mouseenter", function(){


    if($(this).attr("src").indexOf("go.jpg") !== -1) // we check if the path contains the name of the image at all
    {
       var att = $(this).attr("src"); // we then pull the src attr
       att = att.replace("go.jpg", "iPAd.jpg"); //and search for the filename and replace new file name

       // in the end we assign the new imagepath to the src of the hovered image
       $(this).attr("src", att);
    }
});
});

Check this fiddle or the code above:

http://jsfiddle.net/F72h3/

You can change image using condition operator

$(function() {
    $("img")
        .mouseover(function() { 
            this.src = this.src.indexOf('Disabled.png') == -1 ?
               '/CompleteEducation/images/icons/toggleIconDisabled.png' :
               '/CompleteEducation/images/icons/toggleIcon.png';
        })
});

I think problem is here

 var src = $(this).attr("src").match(/[^\.]+/) + "toggleIconDisabled.png"; //this will return "/CompleteEducation/images/icons/toggleIcontoggleIconDisabled.png"

try this

var src = ($(this).attr("src").indexOf("Disabled")>-1)?"/CompleteEducation/images/icons/toggleIcon.png":"/CompleteEducation/images/icons/toggleIconDisabled.png";

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