Javascript 在javascript中淡入淡出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8679614/
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-24 07:02:46  来源:igfitidea点击:

Fade in fade out in javascript

javascriptfunctionsettimeoutfadeinfadeout

提问by Hakan

I continue the work on: https://codereview.stackexchange.com/questions/7315/fade-in-and-fade-out-in-pure-javascript

我继续工作:https: //codereview.stackexchange.com/questions/7315/fade-in-and-fade-out-in-pure-javascript

What is the best way to detect if the fade in or fade out is completed before setting a new function. This is my way, but I guess there is a much better way?

在设置新功能之前检测淡入或淡出是否完成的最佳方法是什么?这是我的方式,但我想有更好的方式吗?

I added the alert's to make it easier for you to see.

我添加了警报以方便您查看。

Why I want to do this is because: If one press the buttons before the for loop has finnished, the animation will look bad.

我为什么要这样做是因为:如果在 for 循环结束之前按下按钮,动画会看起来很糟糕。

I want the buttons to work only when the fadeing is completed.

我希望按钮仅在淡入淡出完成后工作。

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>

<body>
        <div>
        <span id="fade_in">Fade In</span> | 
        <span id="fade_out">Fade Out</span></div>
        <div id="fading_div" style="display:none;height:100px;background:#f00">Fading Box</div>
    </div>
</div>

<script type="text/javascript">
var done_or_not = 'done';

// fade in function
function function_opacity(opacity_value, fade_in_or_fade_out) { // fade_in_or_out - 0 = fade in, 1 = fade out
    document.getElementById('fading_div').style.opacity = opacity_value / 100;
    document.getElementById('fading_div').style.filter = 'alpha(opacity='+opacity_value+')';
    if(fade_in_or_fade_out == 1 && opacity_value == 1)
    {
        document.getElementById('fading_div').style.display = 'none';
        done_or_not = 'done';
        alert(done_or_not);
    }
    if(fade_in_or_fade_out == 0 && opacity_value == 100)
    {
        done_or_not = 'done';
        alert(done_or_not);
    }

}





window.onload =function(){

// fade in click
document.getElementById('fade_in').onclick = function fadeIn() {
    document.getElementById('fading_div').style.display='block';
    var timer = 0;
    if (done_or_not == 'done')
    {
        for (var i=1; i<=100; i++) {
            set_timeout_in = setTimeout("function_opacity("+i+",0)", timer * 10);
            timer++;
            done_or_not = 'not_done'
        }
    }
};

// fade out click
document.getElementById('fade_out').onclick = function fadeOut() {
    clearTimeout(set_timeout_in);
    var timer = 0;
    if (done_or_not == 'done')
    {
        for (var i=100; i>=1; i--) {
            set_timeout_out = setTimeout("function_opacity("+i+",1)", timer * 10);
            timer++;
            done_or_not = 'not_done'
        }
    }
};



}// END window.onload
</script>
</body>
</html>

采纳答案by Peter-Paul van Gemerden

I agree with some of the comments. There are many nice JavaScript libraries that not only make it easier to write code but also take some of the browser compatibility issues out of your hands.

我同意一些评论。有许多不错的 JavaScript 库,它们不仅使编写代码变得更容易,而且还可以解决一些浏览器兼容性问题。

Having said that, you could modify your fade functions to accept a callback:

话虽如此,您可以修改淡入淡出函数以接受回调:

function fadeIn(callback) {
    return function() {
        function step() {
            // Perform one step of the animation

            if (/* test whether animation is done*/) {
                callback();   // <-- call the callback
            } else {
                setTimeout(step, 10);
            }
        }
        setTimeout(step, 0); // <-- begin the animation
    };
}

document.getElementById('fade_in').onclick = fadeIn(function() {
    alert("Done.");
});

This way, fadeInwill return a function. That function will be used as the onclickhandler. You can pass fadeIna function, which will be called after you've performed the last step of your animation. The inner function (the one returned by fadeIn) will still have access to callback, because JavaScript creates a closurearound it.

这样,fadeIn将返回一个函数。该函数将用作onclick处理程序。您可以传递fadeIn一个函数,该函数将在您执行动画的最后一步后被调用。内部函数(由 返回的那个fadeIn)仍然可以访问callback,因为 JavaScript在它周围创建了一个闭包

Your animation code could still use a lot of improvement, but this is in a nutshell what most JavaScript libraries do:

你的动画代码仍然可以使用很多改进,但简而言之,这是大多数 JavaScript 库所做的:

  • Perform the animation in steps;
  • Test to see if you're done;
  • Call the user's callback after the last step.
  • 分步执行动画;
  • 测试看看你是否完成了;
  • 在最后一步之后调用用户的回调。

One last thing to keep in mind: animation can get pretty complex. If, for instance, you want a reliable way to determine the duration of the animation, you'll want to use tween functions (also something most libraries do). If mathematics isn't your strong point, this might not be so pleasant...

要记住的最后一件事:动画可能会变得非常复杂。例如,如果您想要一种可靠的方法来确定动画的持续时间,您将需要使用补间函数(大多数库也这样做)。如果数学不是你的强项,这可能不是那么愉快......



In response to your comment: you say you want it to keep working the same way; "If the function is bussy, nothing shall happen."

回应你的评论:你说你希望它继续以同样的方式工作;“如果函数很忙,什么都不会发生。”

So, if I understand correctly, you want the animations to be blocking. In fact, I can tell you two things:

所以,如果我理解正确,你希望动画被阻塞。其实我可以告诉你两件事:

  1. Your animations aren't blocking (at least, not the animations themselves -- read below).
  2. You can still make it work the way you want with any kind of asynchronous animations.
  1. 您的动画没有被阻塞(至少,不是动画本身——请阅读下文)。
  2. 您仍然可以使用任何类型的异步动画使其按照您想要的方式工作。

This is what you are using done_or_notfor. This is, in fact, a common pattern. Usually a boolean is used (trueor false) instead of a string, but the principle is always the same:

这就是你正在使用done_or_not的。事实上,这是一种常见的模式。通常使用布尔值(truefalse)而不是字符串,但原理始终相同:

// Before anything else:
var done = false;

// Define a callback:
function myCallback() {
    done = true;
    // Do something else
}

// Perform the asynchronous action (e.g. animations):
done = false;
doSomething(myCallback);

I've created a simple example of the kind of animation you want to perform, only using jQuery. You can have a look at it here: http://jsfiddle.net/PPvG/k73hU/

我已经创建了一个你想要执行的动画类型的简单示例,仅使用 jQuery。你可以在这里看看:http: //jsfiddle.net/PPvG/k73hU/

var buttonFadeIn = $('#fade_in');
var buttonFadeOut = $('#fade_out');
var fadingDiv = $('#fading_div');

var done = true;

buttonFadeIn.click(function() {
    if (done) {
        // Set done to false:
        done = false;

        // Start the animation:
        fadingDiv.fadeIn(
            1500, // <- 1500 ms = 1.5 second
            function() {
                // When the animation is finished, set done to true again:
                done = true;
            }
        );
    }
});

buttonFadeOut.click(function() {
    // Same as above, but using 'fadeOut'.
});

Because of the donevariable, the buttons will only respond if the animation is done. And as you can see, the code is really short and readable. That's the benefit of using a library like jQuery. But of course you're free to build your own solution.

由于done变量的原因,按钮仅在动画完成后才会响应。正如您所看到的,代码非常简短且可读。这就是使用像 jQuery 这样的库的好处。当然,您可以自由构建自己的解决方案。

Regarding performance: most JS libraries use tweens to perform animations, which is usually more performant than fixed steps. It definitely looks smoother to the user, because the position depends on the timethat has passed, instead of on the number of stepsthat have passed.

关于性能:大多数 JS 库使用补间来执行动画,这通常比固定步骤的性能更高。它对用户来说肯定看起来更平滑,因为位置取决于经过的时间,而不是经过的步数

I hope this helps. :-)

我希望这有帮助。:-)

回答by stackuser10210

you could move your fade code to its own function

您可以将淡入淡出代码移动到其自己的功能

var alpha = 100
function fade() { 
    if (alpha > 0) {
        alpha -= 1;    
        *your opacity changes*
        (e.g.: .opacity = (alpha/100);
        .style.filter = 'alpha(opacity='+alpha+')';)
    }
    else {
        *complete - modify the click event*
    }
 }

you may want to add .MozOpacity to go with .opacity and .filter. as mentioned in the comments above, though, cancelling or forcing a completed fade may be better than preventing new clicks while the loop's running.

您可能想要添加 .MozOpacity 以配合 .opacity 和 .filter。但是,如上面的评论中所述,取消或强制完成淡入淡出可能比在循环运行时阻止新的点击更好。

ps: i respect you for coding that yourself. javascript libraries are overused and often unnecessary.

ps:我尊重你自己编码。javascript 库被过度使用并且通常是不必要的。

回答by Marecky

It could be resolved in few ways. Please take a look at code at the stub of my home page http://marek.zielonkowski.com/thescript.jsI did it by clearing the time out (I think, I don't remember well because it was few years ago) clearInterval(isMoving);or

它可以通过几种方式解决。请看一下我主页的存根代码 http://marek.zielonkowski.com/thescript.js我是通过清除超时来完成的(我想,我记不太清楚了,因为是几年前的) clearInterval(isMoving);或者

this.fadeIn = function (){
    iCurrentAlpha = (iCurrentAlpha===null) ? alpha : iCurrentAlpha;
    clearInterval(isFading);
    isFading = setInterval(function(){changeFading(1);},timer);
}

Or You can code your custom events and dispatch something like 'onFadeOutStop' to the listener.

或者,您可以编写自定义事件并将诸如“onFadeOutStop”之类的内容发送给侦听器。

And please do not use setTimeout('function_name()') with quotes - because it is bad habbit (set Timeout behaves then like eval which supposed to be evil :)

并且请不要使用带引号的 setTimeout('function_name()') - 因为它是坏习惯(set Timeout 的行为就像 eval 那样应该是邪恶的 :)

回答by Laurence

You should use jquery. you can run a function after an animation

你应该使用jquery。你可以在动画之后运行一个函数

$('#clickthis').click(function(){
     //jquery has really easy way of animating css properties
     //the 5000 is the duration in milliseconds
     $('#animatethis').animate({opacity:0},5000,function(){

         //this will only run once the animation is complete
         alert('finished animating');

     });

     //or use the function..
     $('#animatethis').fadeOut(5000,function(){
          //this will only run once the animation is complete
         alert('finished fading out'); 
     });
});

that should do it. I didn't test it so forgive me if it has any errors.

应该这样做。我没有测试它,所以如果它有任何错误,请原谅我。

-L

-L