简体   繁体   中英

JQuery change image src on mouseover not working in IE7 and 8

I have a set of images which I want the source to change on mouseover. My code works fine in everything except IE 7 and 8 - when I hover over the image it just changes to a broken image link.

My code is:

$(".socialicon").each(function() {
   $(this).find("img")
        .mouseover(function() { 
            var src = $(this).attr("src").match(/[^\.]+/) + "hover.png";
            $(this).attr("src", src);
        })
        .mouseout(function() {
            var src = $(this).attr("src").replace("hover.png", ".png");
            $(this).attr("src", src);
        });
});

Would anyone know if there is something I have to change to have this work in IE 7 and 8?

You should debug on IE7&8 - what is the value of $(this).attr("src") and what src attribute has the element after enter with the mouse over the element? I suppose, that the IE maybe returns an absolute path to the image, like " http://example.com/image.png " - in this case your RegEx would not work.

Why not calling

var src = $(this).attr("src").replace(".png", "hover.png");

instead of

var src = $(this).attr("src").match(/[^\.]+/) + "hover.png";

this would be more consistent regarding the mouseout method.

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