Javascript fade in fade out without Jquery and CSS3

前端 未结 6 521
南方客
南方客 2020-12-03 11:28

I am really squeezing my head to make the simple fade in and fade out of the background image work only with javascript without JQuery and CSS3. I know how easy is to call a

6条回答
  •  独厮守ぢ
    2020-12-03 11:30

    Here are my full implementations of fadeIn and fadeOut for cross-browser support (including IE6) which does not require jQuery or any other 3rd-party JS library:

    function fadeIn( elem, ms )
    {
      if( ! elem )
        return;
    
      elem.style.opacity = 0;
      elem.style.filter = "alpha(opacity=0)";
      elem.style.display = "inline-block";
      elem.style.visibility = "visible";
    
      if( ms )
      {
        var opacity = 0;
        var timer = setInterval( function() {
          opacity += 50 / ms;
          if( opacity >= 1 )
          {
            clearInterval(timer);
            opacity = 1;
          }
          elem.style.opacity = opacity;
          elem.style.filter = "alpha(opacity=" + opacity * 100 + ")";
        }, 50 );
      }
      else
      {
        elem.style.opacity = 1;
        elem.style.filter = "alpha(opacity=1)";
      }
    }
    
    function fadeOut( elem, ms )
    {
      if( ! elem )
        return;
    
      if( ms )
      {
        var opacity = 1;
        var timer = setInterval( function() {
          opacity -= 50 / ms;
          if( opacity <= 0 )
          {
            clearInterval(timer);
            opacity = 0;
            elem.style.display = "none";
            elem.style.visibility = "hidden";
          }
          elem.style.opacity = opacity;
          elem.style.filter = "alpha(opacity=" + opacity * 100 + ")";
        }, 50 );
      }
      else
      {
        elem.style.opacity = 0;
        elem.style.filter = "alpha(opacity=0)";
        elem.style.display = "none";
        elem.style.visibility = "hidden";
      }
    }
    

    As others have said, you need to fix your handleClick to properly select a single element, then pass that element to the fade function (which I named fadeOut for clarity). The default time for a jQuery fade is 400ms, so if you want to mimic that, your call might look like this:

    function handleClick( evt )
    {
      fadeOut( document.getElementById(evt.target.id), 400 );
    }
    

提交回复
热议问题