简体   繁体   中英

javascript fade in fade out doesn't work

Does anyone know why my javascript doesn't work AS IT IS? Below is the code:

function load(){
    function fadein(){
        var op = document.getElementsByClassName("load_1")[0]
        op.style.opacity = 0;
        function animate(){
            if ((op.style.opacity = op.style.opacity + 0.01) < 1){
                alert("Hello")
                requestAnimationFrame(animate);
            }
        }
        animate()
    }
    fadein()
}

load()

I know you said you wanted it to work exactly the way it so, so I apologise if my suggestions are going a bit overboard, but I couldn't get it to work the way you have it for the below reasons:

  1. Nesting the function is not a good practice at least in JavaScript in my opinion as it will many times cause it to not work, as seems to be doing in your case. Tha being said, you can define them separately and call them inside your load function.
  2. the definition of the var op will work better if it is declared outside so it is a shared variable. Otherwise I would suggest passing it as argument between the functions. Depends really on what you are aiming for later on, but the way it is at the moment I noticed that it prevents the other function from seeing it sometimes
  3. Lastly, but possibly most importantly, op.style.opacity is not a number. you can pass a number directly to it, but adding a number to it won't work, as it gets parsed to string to become CSS.

Find below a suggestion code. It has multiple changes but hopefully not too many as you wished for.

 var op = document.getElementsByClassName("load_1")[0];
 load();
 function load(){
     fadein();
     animate();
 }
 function animate(){
      var opac = parseFloat(op.style.opacity);
      opac = opac+0.1;
      op.style.opacity = opac;
      if ((op.style.opacity) < 1){
           alert("Hello");
           requestAnimationFrame(animate);
      }
}
function fadein(){
     op.style.opacity = 0.1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM