我的解决方案不是真正的纯Js,因为它涉及CSS动画,例如@Anarion的动画,但我包括了在0.02
之类的事件上执行此操作所需的Js代码。签出:
[这里,我有一个功能,可在页面加载后立即使带有id="box"
的方框变淡。我尝试过,但是没有找到如何再次在框内淡入淡出,或者只是如何在框内或带有纯JavaScript而不是jQuery的元素中淡入淡出。这是我的fadeOut()
函数代码:
var box = document.getElementById('box');
function fadeOut(elem, speed)
{
if(!elem.style.opacity)
{
elem.style.opacity = 1;
}
setInterval(function(){
elem.style.opacity -= 0.02;
}, speed /50);
}
fadeOut(box, 2000);
#box
{
width: 100px;
height: 100px;
background-color: blue;
}
<div id="box"></div>
[在此先感谢贡献者。欢呼声
我建议使用CSS动画
@-webkit-keyframes fadeout {
0% {opacity:1;}
100% {opacity:0;}
}
@keyframes fadeout {
0% {opacity:1;}
100% {opacity:0;}
}
.fadeOut {
opacity:0;
-moz-animation : fadeout 1s linear;
-webkit-animation: fadeout 1s linear;
animation : fadeout 1s linear;
}
您只需要向元素添加fadeOut类
如果您需要纯JavaScript解决方案,则可以使用此:
http://jsfiddle.net/3weg2zj1/1/
<div id="box"></div>
#box {
width:100px;
height:100px;
background-color:blue;
}
var box = document.getElementById('box');
function fadeOutIn(elem, speed ) {
if (!elem.style.opacity) {
elem.style.opacity = 1;
} // end if
var outInterval = setInterval(function() {
elem.style.opacity -= 0.02;
if (elem.style.opacity <= 0) {
clearInterval(outInterval);
var inInterval = setInterval(function() {
elem.style.opacity = Number(elem.style.opacity)+0.02;
if (elem.style.opacity >= 1)
clearInterval(inInterval);
}, speed/50 );
} // end if
}, speed/50 );
} // end fadeOut()
fadeOutIn(box, 2000 );
setInterval()
调用返回的间隔标识符,以便以后可以取消它。请注意,在上面的代码中,这涉及到outInterval
和inInterval
上的关闭。elem.style.opacity
时遇到了一个奇怪的问题:+=
运算符拒绝工作。经过大约10分钟的坐着和凝视(和一些实验),我终于发现elem.style.opacity
总是被强制为字符串(也许all+
运算符(并扩展为+=
运算符)正在进行字符串连接,在elem.style.opacity += 0.02;
的初始LoC下,它转换为elem.style.opacity = elem.style.opacity+0.02;
,如果我们假设elem.style.opacity
位于[C0 ]转换为'0.02'
,也转换为elem.style.opacity = '0.02'+0.02;
,浏览器JavaScript引擎elem.style.opacity = '0.020.02';
(因为它需要CSS opacity属性的有效数值!)。 ,导致不透明度卡在0.020
上。哇靠!这就是为什么我必须在进行加法之前将强制转换为数字。我的解决方案不是真正的纯Js,因为它涉及CSS动画,例如@Anarion的动画,但我包括了在0.02
之类的事件上执行此操作所需的Js代码。签出:
onclick
function showHelloWorld(){ var helloWorldElement = document.getElementById('hello-world'); helloWorldElement.classList.remove('hide','fade-out'); helloWorldElement.classList.add('fade-in') } function hideHelloWorld(){ var helloWorldElement = document.getElementById('hello-world'); helloWorldElement.classList.add('fade-out'); helloWorldElement.classList.remove('fade-in'); setTimeout(function(){ helloWorldElement.classList.add('hide'); },2000) //Note that this interval matches the timing of CSS animation }
body{ text-align:center; } #hello-world{ font-size:36px; } .hide{ display:none; } .fade-in{ animation: 2s fadeIn; } .fade-out{ animation: 2s fadeOut; } @keyframes fadeIn{ from{ opacity:0; } to{ opacity:1; } } @keyframes fadeOut{ from{ opacity:1; } to{ opacity:0; } }
我的解决方案不是真正的纯Js,因为它涉及CSS动画,例如@Anarion的动画,但我包括了在0.02
之类的事件上执行此操作所需的Js代码。签出: