在纯JavaScript中实现淡入和淡出效果(无需jQuery)

10
我有一个函数,在页面加载时淡化一个具有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>

非常感谢所有的贡献者。谢谢!


可能会有用:https://developer.mozilla.org/zh-CN/docs/Web/Guide/CSS/Using_CSS_transitions - jdphenix
如果您展示了淡入失败的尝试以及您的正常工作代码,可能会有所帮助。 - Quentin
你的时间间隔一直在运行,当不透明度为零时,你需要用 clearInterval 停止它。 - Chris
4个回答

11

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


谢谢,我一定会尝试的。 - J Akhtar

4
如果您希望使用纯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;的代码行下,由于elem.style.opacity处于'0.02',它将变成elem.style.opacity = elem.style.opacity+0.02;,这将变成elem.style.opacity = '0.02' + 0.02;,这将变成elem.style.opacity ='0.020.02';,浏览器JavaScript引擎(啊咳)会将其解析为0.020(因为CSS不透明度属性需要一个有效的数字值!),这导致不透明度一直停留在0.02。太吓人了!这就是为什么我必须在执行加法之前添加强制转换为数字的原因。

0
<!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


仅有代码的答案几乎总是可以从添加一些解释它们如何以及为什么工作中受益。 - Jason Aller

0

我的解决方案并不是纯粹的JS,因为它涉及到类似于@Anarion的CSS动画,但我包含了必要的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;
  }
}
<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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接