简体   繁体   中英

How can i change image source on hover with only CSS

How can i change image source on hover with only CSS

i tried but was able to find only answers with javascript.

this is my code:

<img src="">

i want to change image to 1.gif when user mouse hover it.

you can target the image first. and then from there when user mouser over the image you can change src attribute

  1. target image.
const img = document.getElementById('imgId');
  1. make mouser over event like this
img.addEventListener('mouserover', callback);
  1. then you make your own function like this
function callback(event) {
    if (img.src=== '1.gif') {
       img.src = '2.gif';
    }
}
  1. return the 1.gif image when the mouseout
img.addEventListener("mouseout", anotherCallback);

function anotherCallback(event) {
    if (img.src !== "1.gif") {
        img.src = '1.gif';
    } 
}

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