开发者

Can the source of an image be changed upon rollover using JavaScript?

开发者 https://www.devze.com 2023-04-11 09:30 出处:网络
I have a question on rollover effects using JavaScript. I have read that image sprites (image with another image on its side) can be used with help of CSS offsetting to achieve basic rollover when on

I have a question on rollover effects using JavaScript.

I have read that image sprites (image with another image on its side) can be used with help of CSS offsetting to achieve basic rollover when onmouseover is handled using JS. Have also read about the possibility of changing classes itself using JS (className) to achi开发者_开发问答eve the above effect.

My question is, can I modify the image src itself using JavaScript, to achieve the rollover effect?

A code like this, maybe -

document.getElementByID("button1").onmouseover = rolloverFunction;
function rolloverFunction(){
this.src = "button1-image2.png";
}

I typed something like this to see if the src of the image can be modified upon rollover, but it is not working. Could you please let me know where I am going wrong?


You need the mouseover and mouseout events. mouseover is triggered when hovering in the image, mouseout on leaving the image. Using plain ol' JS would yield:

<img src="default.png" id="image" alt="">

<script>
var image = document.getElementById("image");
image.onmouseover = function () {
    this.src = "rollover.png";
};
image.onmouseout = function () {
    this.src = "default.png";
};
</script>

Or using a common function to avoid duplicating the URL:

function rollover_effect(img_elm, rollover_src) {
    var default_src = img_elm.src;
    img_elm.onmouseover = function () {
        img_elm.src = rollover_src;
    };
    img_elm.onmouseout = function () {
        img_elm.src = default_src;
    };
}
rollover_effect(document.getElementByID("image"), "rollover.png");
0

精彩评论

暂无评论...
验证码 换一张
取 消