淡入和淡出在纯JavaScript中,无需jQuery

fade in and fade out in pure javascript without jquery

本文关键字:无需 jQuery JavaScript 淡出 淡入      更新时间:2024-03-03

在这里,我有一个函数,可以在页面加载后立即淡化带有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;
}

您只需要向元素添加淡出类

如果你想要一个纯粹的JavaScript解决方案,你可以使用这个:

http://jsfiddle.net/3weg2zj1/1/

.HTML

<div id="box"></div>

.CSS

#box {
    width:100px;
    height:100px;
    background-color:blue;
}

JavaScript

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()调用返回的间隔标识符,以便以后可以取消它。请注意,在上面的代码中,这涉及在outIntervalinInterval上关闭。
  • 对于此特定代码,您可以测试不透明度何时达到或低于较低阈值(我使用了零(,然后清除现有的间隔过程,并启动一个新的过程来反转动画。
  • 在反向间隔过程中,可以增加不透明度,然后根据上限阈值进行测试,以确定何时清除新的间隔过程。
  • 我在尝试增加elem.style.opacity时遇到了一个奇怪的问题:+=操作员拒绝工作。经过大约 10 分钟的坐着凝视(以及一些实验(,我终于发现elem.style.opacity总是被迫成为一个字符串(也许所有 CSS 链接的属性以这种方式运行......(,因此+运算符(以及扩展的 += 运算符(正在执行字符串连接,在 elem.style.opacity += 0.02; 的天真 LoC 下, 正在变成elem.style.opacity = elem.style.opacity+0.02;,如果我们假设elem.style.opacity'0.02',它正在变成elem.style.opacity = '0.02'+0.02;,它正在变成elem.style.opacity = '0.020.02';,浏览器JavaScript引擎(咳咳(慷慨地解析为0.020(因为它需要CSS不透明度属性的有效数值!(,这导致不透明度卡在0.02。天哪!这就是为什么我必须在添加之前添加演员表的原因。

我的解决方案并不是真正的纯 Js,因为它涉及像 @Anarion 这样的 CSS 动画,但我包含了在 onclick 等事件上执行此操作所需的 Js 代码。看看吧:

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;
  }
}
<div id="hello-world" class="hide">Hello World</div>
<br>
<button onclick="showHelloWorld()">Click Here To Fade In</button>
<button onclick="hideHelloWorld()">Click Here To Fade Out</button>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>pure javascript</title>
    <link rel="stylesheet" href="2.css">
</head>
<body>
    <script type="text/javascript" src="jquery-3.js"></script>
    <script type="text/javascript"> //begging of js
         let mydiv =document.createElement("div") //creating div
         let divtxt=window.document.createTextNode("hover me") //creating text node 
         mydiv.appendChild(divtxt) //now div with "hover me" text
         document.body.insertBefore(mydiv,document.body.childNodes[0])//insert before the script line in html
         mydiv.style.width="100px" //styling the div to 100px
         mydiv.style.fontSize="1.5em" //stylling the div with font Size
         mydiv.style.backgroundColor="yellow" //div has backgroundColor yellow
         let myp   =document.createElement("p") //create paragraph
         let ptxt=document.createTextNode("hello there") //create text node
         myp.appendChild(ptxt) //now p with "hello there" txt
         document.body.insertBefore(myp,document.body.childNodes[1]) //insert before script line in html
         let opacity=1; //begining with real work with opacity equal to 1 
          mydiv.onmouseenter=()=>{ //on mouseover main func that has 2 funcs one for reducing the opacity and another for terminate the process 
            mo=()=>{//child func to lower the opacity
            opacity-=.01 //lowering opacity by .01 every 10 mili sec
          myp.style.opacity=opacity//the actual fading happen here where the p is reduced
          }
       let x = setInterval(mo,10) //interval to make the func act as a loop and take x to clear it up later
        mo1=()=>{//secound func to terminate the first func
            clearInterval(x) //clear the first func after 980 mili sec
          myp.style.removeProperty("opacity")//removing opacity proberty 
          myp.style.display="none"//adding dispaly property and equall to none
         }
         setTimeout(mo1,980) //terminate the first func in 980 mili sec
          }
          mydiv.onmouseleave=()=>{ //second main func on mouseleave
            myp.style.removeProperty("display")//fisrt we got to remove dispaly none and raise the opacity
        mo=()=>{func to raise the opacity
          myp.style.removeProperty("display")//why i added it again just to make sure display property is removed
          opacity+=.01//increase opacity by .01
         myp.style.opacity=opacity//equalling the opacity of p  with the new opacity 
         }
        let y = setInterval(mo,10) //make the function to act as loop again 
       mo1=()=>{//sec func to terminate the first func
         clearInterval(y)//clearing the fisrt function
           myp.style.removeProperty("opacity")//remove opacity property
       }
        setTimeout(mo1,980)//wiaiting to stop the first func
      }
    </script>//end
</body>
</html>

纯JavaScript