通过使用Javascript设置不透明度来淡入元素 [英] Fade in element by setting opacity with Javascript

查看:82
本文介绍了通过使用Javascript设置不透明度来淡入元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我决定使用香草javascript创建淡入淡出的动画效果。

I have decided to create a fade in animation effect using vanilla javascript.

这是我淡入淡出的代码:

This is the code for my fade in effect:

document.querySelector('.open-1_1').onclick = function() {

    document.getElementById('about-frame').style.display = 'block';     

    for (opacity = 0; opacity < 1.1; opacity = opacity + 0.1) 
    {           
        setTimeout(function(){document.getElementById('about').style.opacity = opacity;},100)                       
    }       
};

我要做的是将#about div的不透明度从0逐渐增加到1在for循环中运行,该循环应该为循环的每次迭代等待100毫秒

What I am trying to do is incrementally increasing the opacity of the #about div from 0 to 1 by running through a for loop which is supposed to wait 100 miliseconds for every iteration of the loop

但是#about div在设置的时间后从黑暗变为不透明1

However the #about div goes from dark to opacity 1 after a set time without seeing the fade in effect.

我的逻辑怎么了?

推荐答案

此for循环没有延迟,它将10个超时设置为100毫秒。

This for loop is not on a delay, it sets ten timeouts to take place in 100 miliseconds.

for (opacity = 0; opacity < 1.1; opacity = opacity + 0.1) 
{           
    setTimeout(function(){document.getElementById('about').style.opacity = opacity;},100)                       
}  

因此,淡入仅需1毫秒。

So the fade only takes 1 ms.

另一方面,这需要一秒钟使MyFadeFunction循环10次。

This on the other hand loops the MyFadeFunction 10 times over a one second period, which is what you are asking for.

var opacity = 0;

function MyFadeFunction() {
   if (opacity<1) {
      opacity += .1;
      setTimeout(function(){MyFadeFunction()},100);
   }
   document.getElementById('about').style.opacity = opacity;
}

http://jsfiddle.net/dL02zqku/1/

注意 var opacity 和 MyFadeFunction() 是全局 ,不是嵌套在启动函数中,而是通过函数调用来调用。这样一来,用于调用该函数的jquery库不会保持在关闭状态。

Note var opacity in this example and MyFadeFunction() are global, not nested within the startup function, but called via a function call. This is so that the jquery library being used to call the function is not held in a closure state.

这篇关于通过使用Javascript设置不透明度来淡入元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆