首页 > 解决方案 > 如何用 JS 播放动画

问题描述

我在按钮悬停时编码淡入和淡出文本......我必须调用动画悬停......我该怎么做?

const button = document.getElementById("btn");
const disp_text = document.getElementById('disp_text');

button.onmouseover = function(){
 //Here goes the animation to play
 disp_text.innerText = "Next";
}

我试过了:

const button = document.getElementById("btn");
const disp_text = document.getElementById('disp_text');

button.onmouseover = function(){
 animation.Play("fadein");
 disp_text.innerText = "Next";
}

但没什么...

如果有人可以提供帮助,我将不胜感激...

标签: javascriptjquerycss-animationsonmouseover

解决方案


下面是一些使用 javascript 在按钮悬停时为淡入淡出动画的代码。我还实现了一个纯 CSS 版本。我正要使用 Animate API 实现一个版本,但我看到 @DEEPAK 已经做到了,所以这是第三种选择。

const button = document.getElementById("btn");
const disp_text = document.getElementById('disp_text');


button.onmouseover = function(){
  disp_text.classList.add('button-hover');
}

button.onmouseout = function(){
  disp_text.classList.remove('button-hover');
}
#disp_text {
  opacity:0;
  transition: opacity .25s ease-in-out;
}
#disp_text.button-hover {
  opacity:1;
}

#disp_text2 {
  opacity:0;
  transition: opacity .25s ease-in-out;
}
#btn2:hover #disp_text2 {
  opacity:1;
}
<button id='btn'>Hover over this to see the animation of the DIV below</button>
<p id='disp_text'>Next</p>

<p>The one below uses css only - no javascript. This is easy because the span is inside the button</p>
<button id='btn2'><span id='disp_text2'>Next</span></button>


推荐阅读