如何用纯 JavaScript 制作淡出效果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29017379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:45:10  来源:igfitidea点击:

How to make fadeOut effect with pure JavaScript

javascriptfadeout

提问by Anakin

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

我正在尝试div使用纯 JavaScript为 a 制作淡入淡出效果。

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.

div 应该平滑地淡出,但它会立即消失。

What's wrong? How can I solve it?

怎么了?我该如何解决?

jsbin

jsbin

回答by Juan Mendes

Initially when there's no opacity set, the value will be an empty string, which will cause your arithmetic to fail. That is, "" < 0.1 == trueand your code goes into the clearIntervalbranch.

最初当没有设置不透明度时,该值将是一个空字符串,这将导致您的算术失败。也就是说,"" < 0.1 == true您的代码进入clearInterval分支。

You can default it to 1 and it will work.

您可以将其默认为 1,它会起作用。

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)

在进行算术和比较时,一个空字符串似乎被 JavaScript 视为 0(即使在 CSS 中它将该空字符串视为完全不透明)

> '' < 0.1
> true

> '' > 0.1
> false


> '' - 0.1
> -0.1

Simpler ApproachWe can now use CSS transitionsto make the fade out happen with a lot less code

更简单的方法我们现在可以使用CSS transitions以更少的代码实现淡出

const target = document.getElementById("target");

target.addEventListener('click', () => target.style.opacity = '0');
// If you want to remove it from the page after the fadeout
target.addEventListener('transitionend', () => target.remove());
#target {
    height: 100px;
    background-color: red;
    transition: opacity 1s;
}
<p>Some text before<p>
<div id="target">Click to fade</div>
<p>Some text after</p>

回答by Lucas Ferreira

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

就在今天早上,我在http://vanilla-js.com 上发现了这段代码,它非常简单、紧凑且快速:

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 setTimeOutfunction.

您可以通过更改setTimeOut函数中的第二个参数来更改淡入淡出的速度。

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>

回答by Alexander Tarasenko

It looks like you can do it another way(I may be wrong).

看起来你可以用另一种方式来做(我可能错了)。

event.target.style.transition = '0.8s';
event.target.style.opacity = 0;

回答by Vikash

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

您可以使用 CSS 过渡属性,而不是在 javascript 中执行 vai 计时器。与您正在做的事情相比,这更注重性能。

check

查看

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

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

回答by Guryash Singh

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