如何在onmouseover javascript函数中添加动画(悬停时更改图像)



我一直在尝试一个函数,当鼠标悬停在照片上时,它会发生变化。有没有办法使这种变化生动起来?

<img src='./images/rocks.jpg' onmouseover="this.src='./images/seasky.jpg';" 
onmouseout="this.src='./images/rocks.jpg';" />

首先,不应使用内联HTML事件属性(即onmouseover、onmouseout等(。这类属性的使用一直持续到今天,因为像W3 Schools这样的网站仍然会显示它们,数以百万计缺乏经验的开发人员只是复制/粘贴他们在其他地方看到的代码,而且因为它似乎有效,他们不会三思而后行。事实上,这些属性应该突然消亡的原因有很多。

现在,对于您的具体问题,如果您想要过渡效果,您需要使用CSS进行设置。而且,最好使用div元素的背景图像,而不是改变img元素的src

详见评论:

/* Separate your event handling code from your markup */
// Get a reference to the element
let fancy = document.querySelector(".fancyImage");
// Set up the mouseover event handler
fancy.addEventListener("mouseover", function(){
this.classList.add("go");       // Change to the Go image
this.classList.remove("stop");  // Remove the Stop image
});
fancy.addEventListener("mouseout", function(){
this.classList.add("stop");     // Change to the Stop image
this.classList.remove("go");    // Remove the Go image
});
/* Use CSS for all styling and layout */
.fancyImage {
/* Set up a transition for all property changes that takes place over 1 second */
transition:all 1s; 

/* Set the size of the div, otherwise it will collapse because there's no content
in its foreground */
width:200px;
height:160px;
}
/* The element starts off with the stop class hard-coded, so it starts with this image */
.fancyImage.stop { 
background: url("https://img.favpng.com/15/11/21/stop-sign-traffic-sign-clip-art-png-favpng-YVm6TAKXcApfNG5qQLT1Axke0.jpg");
/* Make the image fit into the element */
background-size:contain;
background-repeat:no-repeat;
}
/* This class gets dynamically added on mouse over */
.fancyImage.go {
background: url("https://theblogreaders.com/wp-content/uploads/2015/12/Go-298x300.gif");

background-size:contain;
background-repeat:no-repeat;
}
<!-- Don't use HTML event attributes or self-terminating tags.
See how much cleaner the HTML is now? -->
<div class="fancyImage stop">

最新更新