javascript - 如何将动画添加到 onmouseover javascript 函数(悬停时更改图像)?

标签 javascript html css

我一直在尝试一个功能,当鼠标悬停在照片上时,它会发生变化。有没有办法让这种变化动画化?

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

最佳答案

首先,内联HTML event attributes (i.e. onmouseover, onmouseout, etc.) should not be used 。这些属性的使用至今仍然存在,因为像 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">

关于javascript - 如何将动画添加到 onmouseover javascript 函数(悬停时更改图像)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60951714/

相关文章:

javascript - 确定 if 语句中是否选择了任何选项

javascript - 自定义媒体流

css 背景图像无法在 iphone 上显示,也无法在桌面以外的任何设备上正常显示

jquery - 语言切换 - 使用 HTML 而不是 Key

html - 我怎样才能 "contain"背景图片?

javascript - 如何将 tabPanel 之一移动到 Shiny-App 中的网页右侧

javascript - 关闭滚动覆盖

javascript - 如何在页面向下滚动时让图像获得不透明度

html - 在手机和平​​板电脑上隐藏页脚

html - 为容器设置 CSS 渐变