开发者

Why won't this script work as a fadeout animation effect

开发者 https://www.devze.com 2023-03-03 18:32 出处:网络
This would be in a javascript function; with an onclick event handler or something. Then onclick it would fadeout what ever the id for box is using the document.getElementsById() object so why won\'t

This would be in a javascript function; with an onclick event handler or something. Then onclick it would fadeout what ever the id for box is using the document.getElementsById() object so why won't it fadeout? Like I have seen quite a lot of effects do? Also note I'm trying to do this with out jquery or any of the plugins as I'm trying to learn and master javascript.

setTimeout(function() {
        for(var i = 1; i< 9; i++) {
         开发者_运维技巧   setTimeout(function() {
            box.style.opacity = '0.'+i; 
            }, 100);
        }
        }, 1000);


You should be calling that function recursively, like this:

    var box = document.getElementById('box');
    var i = 10;
    function fadeOut() {
        if (i>0) {
            i--;
            box.style.opacity = '0.'+i; 
            setTimeout(fadeOut, 100);
        }
    }
    setTimeout(fadeOut, 1000);


A few things:

1) You're actually fading the box in by increasing the opacity rather than fading it out by decreasing the opacity.

2) You're setting all the setTimeout functions at the same time, in the inner call you probably want to call a setInterval and have that increment i. Or, you could pile up the setTimeouts by setting the timing at 100*i rather than just 100.


It wasn't really clear in your question but probably seeing it at 0.9 opacity instantly. The reasoning is that the for loop doesn't actually give you the value of i within the loop, only the address in which to access it. That's fine if you actually use it within the body of the for loop, but you're not doing that. When you set the timeout, by the time the timeout is called it's already finished iterating through the for loop and i is 9. Because of this, each timeout is only going to be setting the opacity to 0.9.

To fix this, you can wrap it in an automatically executed anonymous function, which passes in the value of i. Doing so will cause the anonymous function to scope i, and allow it to be accessed by the timeout when it's called.

setTimeout(function() {
    for (var i = 1; i < 9; i++) (function(i) {
        setTimeout(function() {
            box.style.opacity = '0.' + i;
        }, 100);
    }(i) // (i) at the end automatically executes, with the argument of i
}, 1000);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号