简体   繁体   中英

JavaScript fading effect for div

This is my code:

var elem = document.getElementById("script_"+el);
elem.style.opacity = 0.5;
elem.style.transition = "opacity 1s";

I then later on down in the code have

elem.style.opacity = 1;

I was expecting the div to first load the opacity (0.5), then load the higher opacity and add the transition effect and move from the Opacity 0.5 -> 1, I saw this happen in a JavaScript tutorial but it doesn't seem to be working for my div and my content.

You have to give a delay after setting the transition property,

  var elem = document.getElementById("script_"+el);
  elem.style.opacity = 0.1;
  elem.style.transition = "opacity 1s";
  setTimeout(function(){ elem.style.opacity = 1;} , 50);

DEMO

Or the best way would be adding that transition through css. That would not expect the engine to make some delay before detecting the target property.

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