简体   繁体   中英

adding mouseover event to img element doesn't work

this is my html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <link href="style.css" rel="stylesheet" type="text/css" />
    <script src="script.js"></script>
  </head>
  <body onload="load();">
    <img src="img1.png">
    <img src="img2.png">
    <img class="img3" src="img3.png">
  </body>
</html>

And I want the 3rd image to go to the left when mouse is over it. (It has position: absolute; on it) using this js code

let img;
function load(){
  img = document.querySelector(".img3");
  img.addEventListener("mouseover", mouseover);
}
function mouseover(){
  img.style.left = "0px";
}

but mouseover never gets called. (Checked with logging)

In your css you can use

.img3:hover{
  /* css here */
}

If you use this method you do not need to use Javascript to change css on hover it is built in to css already :)

you can use the hover method in css to achieve this, it would look something like:

.img3:hover {
  width: *put desired width here*;
  height: *put desired height here*;
}

You might need to use id tags to make the default image shrink when the img3:hover event occurs. You can find more information about it here: https://developer.mozilla.org/en-US/docs/Web/CSS/:hover

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