javascript中的淡入淡出

发布于 2024-12-23 14:47:20 字数 2407 浏览 1 评论 0原文

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

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

我添加了警报,以便您更容易看到。

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

我希望按钮仅在淡入淡出完成时才起作用。

<!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 continue the work on: 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.

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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

地狱即天堂 2024-12-30 14:47:20

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

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

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.");
});

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

您的动画代码仍然需要大量改进,但这就是大多数 JavaScript 库所做的简而言之:

  • 分步执行动画;
  • 测试一下是否完成;
  • 最后一步后调用用户的回调。

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


针对你的评论:你说你希望它继续以同样的方式工作; “如果函数很忙,则不会发生任何事情。”

因此,如果我理解正确的话,您希望动画被阻塞。事实上,我可以告诉你两件事:

  1. 你的动画没有阻塞(至少动画本身没有阻塞——请阅读下文)。
  2. 您仍然可以使用任何类型的异步动画使其按照您想要的方式工作。

这就是您使用 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);

我创建了一个简单的动画示例想要执行,只能使用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'.
});

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

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

我希望这有帮助。 :-)

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.

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. That function will be used as the onclick handler. You can pass fadeIn a 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 closure around it.

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

  • 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. 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:

// 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/

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

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 time that has passed, instead of on the number of steps that have passed.

I hope this helps. :-)

温柔戏命师 2024-12-30 14:47:20

您可以将淡入淡出代码移至其自己的函数中,

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*
    }
 }

您可能需要添加 .MozOpacity 以与 .opacity 和 .filter 一起使用。不过,正如上面评论中提到的,取消或强制完成淡入淡出可能比在循环运行时阻止新的点击更好。

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

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.

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

雪落纷纷 2024-12-30 14:47:20

可以通过几种方式解决。请查看我主页存根中的代码
http://marek.zielonkowski.com/thescript.js
我通过清除超时来做到这一点(我想,我不太记得了,因为那是几年前的事了)
clearInterval(isMoving);
或者

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

或者您可以编写自定义事件并将“onFadeOutStop”之类的内容分派给侦听器。

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

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);
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.

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 :)

紫竹語嫣☆ 2024-12-30 14:47:20

你应该使用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'); 
     });
});

您可以在应该执行此操作的 。我没有测试过,如果有任何错误,请原谅我。

-L

You should use 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文