How to make fadeOut effect with pure JavaScript

2019-01-17 16:23发布

问题:

I'm trying to make fadeOut effect for a div with pure JavaScript.

This is what I'm currently using:

//Imagine I want to fadeOut an element with id = "target"
function fadeOutEffect()
{
 var fadeTarget = document.getElementById("target");
 var fadeEffect = setInterval(function() {
  if (fadeTarget.style.opacity < 0.1)
  {
   clearInterval(fadeEffect);
  }
  else
  {
   fadeTarget.style.opacity -= 0.1;
  }
 }, 200);
}

The div should fade-out smoothly, but it immediately disappear.

What's wrong? How can I solve it?

jsbin

回答1:

Initially when there's no opacity set, the value will be an empty string, which will cause your arithmetic to fail. You can default it to 1 and it will work.

function fadeOutEffect() {
    var fadeTarget = document.getElementById("target");
    var fadeEffect = setInterval(function () {
        if (!fadeTarget.style.opacity) {
            fadeTarget.style.opacity = 1;
        }
        if (fadeTarget.style.opacity > 0) {
            fadeTarget.style.opacity -= 0.1;
        } else {
            clearInterval(fadeEffect);
        }
    }, 200);
}

document.getElementById("target").addEventListener('click', fadeOutEffect);
#target {
    height: 100px;
    background-color: red;
}
<div id="target">Click to fade</div>

An empty string seems like it's treated as a 0 by JavaScript when doing arithmetic and comparisons (even though in CSS it treats that empty string as full opacity)

> '' < 0.1
> true

> '' > 0.1
> false


> '' - 0.1
> -0.1


回答2:

Just this morning I found this piece of code at http://vanilla-js.com, it's very simple, compact and fast:

var s = document.getElementById('thing').style;
s.opacity = 1;
(function fade(){(s.opacity-=.1)<0?s.display="none":setTimeout(fade,40)})();

You can change the speed of the fade changing the second parameter in the setTimeOut function.

var s = document.getElementById('thing').style;
s.opacity = 1;
(function fade(){(s.opacity-=.1)<0?s.display="none":setTimeout(fade,40)})();
#thing {
  background: red;
  line-height: 40px;
}
<div id="thing">I will fade...</div>



回答3:

you can use CSS transition property rather than doing vai timer in javascript. thats more performance oriented compared to what you are doing.

check

http://fvsch.com/code/transition-fade/test5.html#test3



回答4:

    var op = 1;
    var element = document.getElementById('exitModal');
    function closeModal() {
        window.setInterval(function(){
            element.style.opacity = op;
            op = op - 0.01;
        },10);