簡體   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