简体   繁体   English

淡入淡出javascript

[英]Fade in fade out in javascript

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>

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, fadeIn will return a function. 这样, fadeIn将返回一个函数。 That function will be used as the onclick handler. 该函数将用作onclick处理程序。 You can pass fadeIn a function, which will be called after you've performed the last step of your animation. 您可以传递fadeIn函数,该函数将在您执行动画的最后一步后调用。 The inner function (the one returned by fadeIn ) will still have access to callback , because JavaScript creates a closure around it. 内部函数(由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. 您仍然可以使用任何类型的异步动画使其按您希望的方式工作。

This is what you are using done_or_not for. 这就是你正在使用的done_or_not This is, in fact, a common pattern. 事实上,这是一种常见的模式。 Usually a boolean is used ( true or false ) instead of a string, but the principle is always the same: 通常使用布尔值( 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. 我已经创建了一个简单的动画类型示例,仅使用jQuery。 You can have a look at it here: http://jsfiddle.net/PPvG/k73hU/ 您可以在这里查看: 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 done variable, the buttons will only respond if the animation is done. 由于已done变量,按钮仅在动画完成时才会响应。 And as you can see, the code is really short and readable. 正如您所看到的,代码非常简短且易读。 That's the benefit of using a library like jQuery. 这是使用像jQuery这样的库的好处。 But of course you're free to build your own solution. 但是你当然可以自由地构建自己的解决方案。

Regarding performance: most JS libraries use tweens to perform animations, which is usually more performant than fixed steps. 关于性能:大多数JS库使用补间来执行动画,这通常比固定步骤更高效。 It definitely looks smoother to the user, because the position depends on the time that has passed, instead of on the number of steps that have passed. 它对用户来说肯定看起来更流畅,因为位置取决于已经过去的时间 ,而不是已经过的步数

I hope this helps. 我希望这有帮助。 :-) :-)

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. 您可能希望添加.MozOpacity以使用.opacity和.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. 但是,如上面的评论所述,取消或强制完成淡入淡出可能比在循环运行时防止新点击更好。

ps: i respect you for coding that yourself. ps:我尊重你自己编码。 javascript libraries are overused and often unnecessary. javascript库被过度使用并且通常是不必要的。

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.js I did it by clearing the time out (I think, I don't remember well because it was few years ago) clearInterval(isMoving); 请看看我主页的存根上的代码http://marek.zielonkowski.com/thescript.js我是通过清除超时来做到的(我想,我记不太清楚了,因为它是在几年前) clearInterval(isMoving); or 要么

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()') - 因为它是不好的habbit(设置Timeout行为就像eval那应该是邪恶的:)

You should use jquery. 你应该使用jquery。 you can run a function after an animation 你可以在动画后运行一个函数

$('#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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM