/* 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">
1条答案
按热度按时间9ceoxa921#
首先,内联HTML事件属性(例如onmouseover、onmouseout等)。这些属性的使用一直持续到今天,因为像W3 Schools这样的网站仍然会显示它们,而且数以百万计的缺乏经验的开发人员只是复制/粘贴他们在其他地方看到的代码,因为这看起来很有效,他们不会三思。事实上,有许多理由可以解释为什么这些品质应该以它们应得的方式突然消亡。
现在,对于你的具体问题,如果你想要一个过渡效果,你需要使用CSS来设置它。而且,最好的方法可能是使用
div
元素的背景图像,而不是修改img
元素的src
。详情见备注: