fade in and fade out in pure javascript without jquery

后端 未结 4 1290
情深已故
情深已故 2021-01-05 10:13

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

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-05 10:31

    My solution is not really pure Js as it involves CSS animation like that of @Anarion but I included Js codes that is needed to do this on events like onclick. Check it out:

    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;
      }
    }
    Hello World

提交回复
热议问题