繁体   English   中英

“切换状态” -javascript中的变量?

[英]“Toggle state”-variable in javascript?

我正在尝试使用布尔值设置变量(currentState),但似乎条件条件中无法识别该变量。 我想念什么?

function toggle(customID) { // Function set on button, 'customID' is the ID
                            // of element to toggle with button. Ex:
                            // <button onclick="(toggle('menu')">Button</button>
    var theToggledElement = document.getElementById(customID);
    var currentState = false; // false = hidden. true = visible.

    if (currentState === false) {
        currentState = true;
        theToggledElement.style.left = '0px';
        console.log('State set to "visible" and left to "0px"');
    }
    else if (currentState === true) {
        currentState = false;
        theToggledElement.style.left = 'calc(-100% + (0.5cm + 1.461544602cm + .5cm))';
        console.log('State set to "hidden" and left to "calc(-100% + (0.5cm + 1.461544602cm + .5cm))"')
    }
}

在此处输入图片说明

@Barmar谢谢! 像这样将“ currentState”变量移到外部:

var currentState = false; // false = hidden. true = visible.
function toggle(customID) { // Function set on button, 'customID' is the ID
                            // of element to toggle with button. Ex:
                            // <button onclick="(toggle('menu')">Button</button>
    var theToggledElement = document.getElementById(customID);

    if (currentState === false) {
        currentState = true;
        theToggledElement.style.left = '0px';
        console.log('State set to "visible" and left to "0px"');
    }
    else if (currentState === true) {
        currentState = false;
        theToggledElement.style.left = 'calc(-100% + (0.5cm + 1.461544602cm + .5cm))';
        console.log('State set to "hidden" and left to "calc(-100% + (0.5cm + 1.461544602cm + .5cm))"')
    }
}

暂无
暂无

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

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