【问题标题】:How to play an Animation with JS如何用 JS 播放动画
【发布时间】:2021-05-13 10:48:49
【问题描述】:

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

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";
}

但是什么都没有……

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

【问题讨论】:

  • 这是从哪里来的:animation.Play("fadein");?悬停时文本会改变吗?

标签: javascript jquery css-animations onmouseover


【解决方案1】:

这里有一些代码在按钮悬停时使用 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>

【讨论】:

    【解决方案2】:

    .play() 仅在您提到如何animate 时才有效

    const button = document.getElementById("btn");
    const disp_text = document.getElementById('disp_text');
    
    button.onmouseover = function(){
     disp_text.innerText = "Next";
     
     const animation = disp_text.animate(
    [
      { opacity: 0 },
      { opacity: 1 }
    ], {
      easing: 'ease',
      duration: 2000
    });
    
     animation.play();
    }
    <button id="btn">Hello</button>
    <p id="disp_text"></p>

    【讨论】:

      【解决方案3】:

      我不确定您所说的“animation.fadeIn”是什么意思。据我所知,原版 JS 中没有名为“动画”的对象。

      编写淡入淡出动画的一种方法是使用 CSS 属性 opacity。

      如果你要用 CSS 编写这个动画,你可以这样做:

      #btn {opacity: 0.5; }
      #btn:hover {opacity: 1} 
      

      如果这是您需要的,请告诉我。

      【讨论】:

        猜你喜欢
        • 2020-06-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-28
        • 1970-01-01
        • 2023-03-31
        • 1970-01-01
        相关资源
        最近更新 更多