在没有jQuery的纯JavaScript中淡入和淡出 [英] fade in and fade out in pure javascript without jquery

查看:92
本文介绍了在没有jQuery的纯JavaScript中淡入和淡出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里,我有一个功能,可在页面加载后立即用id="box"淡出一个方形框.我尝试了一下,但没有找到如何再次在框内淡入淡出,或者只是如何在框内或带有纯JavaScript而不是jQuery的元素上淡入淡出. 这是我的fadeOut()函数代码:

Here I have a function that fades a square box with id="box" as soon as the page loads. I tried but failed to find out how to fade in the box again or simply how to fade in a box or an element with pure JavaScript not jQuery. Here is my code for fadeOut() function:

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>

在此先感谢贡献者.欢呼

Many thanks in advance to contributors. cheers

推荐答案

我建议使用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类

You only need to add fadeOut class to the element

这篇关于在没有jQuery的纯JavaScript中淡入和淡出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆