Can't get global variables inside the function

2020-05-08 07:07发布

问题:

var selection = document.getElementById('selection');
var closed = true;

function openorclosebar() {

    if(closed == false){
        selection.style.webkitAnimation='bounceOutDown 1s forwards';
        selection.style.animation='bounceOutDown 1s forwards';
        closed = false;
    }
    else{
        selection.style.webkitAnimation='bounceInUp 1s forwards';
        selection.style.animation='bounceInUp 1s forwards';
        closed = true;
    };
}

How can I get global variables "selection" and "closed" to use them. I tried "window.selection" and "window.closed", but nothing helps. If you have an idea, help me please, it's so important project.

回答1:

The global closed variable is read-only: It's the windows .closed property - such has happened before with .name :-)

Use an IEFE to make your variable local:

(function() {
    var selection = document.getElementById('selection');
    var closed = true;

    function openorclosebar() {
        if(!closed) {
            selection.style.webkitAnimation='bounceOutDown 1s forwards';
            selection.style.animation='bounceOutDown 1s forwards';
            closed = false;
        } else {
            selection.style.webkitAnimation='bounceInUp 1s forwards';
            selection.style.animation='bounceInUp 1s forwards';
            closed = true;
        }
    }
}());

Also have a look at other unsafe names in browser environments.