淡入淡出并在没有jquery的纯JavaScript中淡出

kni*_*ght 6 javascript fade fadeout fadein

在这里,我有一个功能,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);
Run Code Online (Sandbox Code Playgroud)
#box
{
  width: 100px;
  height: 100px;
  background-color: blue;
  }
Run Code Online (Sandbox Code Playgroud)
<div id="box"></div>
Run Code Online (Sandbox Code Playgroud)

非常感谢贡献者.干杯

Ana*_*ion 6

我建议使用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;
}
Run Code Online (Sandbox Code Playgroud)

您只需要向元素添加fadeOut类