问题描述
我正在编写按钮悬停时的淡入和淡出文本...我必须在悬停时调用动画...我该怎么做?
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";
}
但没什么...
如果有人能帮忙,我将不胜感激...
解决方法
以下是一些代码,当按钮悬停时,它使用 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>
我不确定您所说的“animation.fadeIn”是什么意思。据我所知,vanilla JS 中没有名为“animation”的对象。
一种编写淡入淡出动画的方法是使用 CSS 属性 opacity。
如果您要在 CSS 中编写此动画,您可以这样做:
#btn {opacity: 0.5; }
#btn:hover {opacity: 1}
如果这是您需要的,请告诉我。
,.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>