纯JavaScript淡入功能 [英] Pure JavaScript fade in function

查看:184
本文介绍了纯JavaScript淡入功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨朋友,当我点击另一个div时,我想淡入div,为此我使用下面的代码。 Code1 工作正常,但我需要使用 Code2

Hi friends i want to fade in a div when i click on another div and for that i am using following code. Code1 works fine but i require to use the Code2.

我知道有jQuery但我需要做这在JavaScript中

I know there is jQuery but i require to do this in JavaScript

你能指导我,我正在做什么样的错误或者我需要改变什么......

Can you guide me that what kind of mistake i am doing or what i need change...

Code1 ---工作正常

function starter() { fin(); }

function fin()
{
    for (i = 0; i <= 1; i += 0.01)
    {
        i=Math.round(i*100)/100;
        setTimeout("seto(" + i + ")", i * 1000);
    }
}

function seto(opa)
{
    var ele = document.getElementById("div1");
    ele.style.opacity = opa;
}

Code2 ---不起作用

function starter()
{
    var ele = document.getElementById("div1");
    fin(ele);
}
function fin(ele)
{
    for (i = 0; i <= 1; i += 0.01)
    {
        i=Math.round(i*100)/100;
        setTimeout("seto(" + ele + "," + i + ")", i * 1000);
    }
}

function seto(ele,opa)
{
    ele.style.opacity = opa;
}


推荐答案

基于网站

EDIT-1

添加了功能,以便用户可以指定动画持续时间(@Marzian评论)


你可以试试这个:

EDIT-1
Added the functionality so that user can specify the animation duration(@Marzian comment)

You can try this:

function fadeIn(el, time) {
  el.style.opacity = 0;

  var last = +new Date();
  var tick = function() {
    el.style.opacity = +el.style.opacity + (new Date() - last) / time;
    last = +new Date();

    if (+el.style.opacity < 1) {
      (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
    }
  };

  tick();
}

var el = document.getElementById("div1");
fadeIn(el, 3000); //first argument is the element and second the animation duration in ms

DEMO

这篇关于纯JavaScript淡入功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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