首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在javascript中“切换状态”-variable?

在javascript中“切换状态”-variable?
EN

Stack Overflow用户
提问于 2018-06-23 06:22:58
回答 1查看 388关注 0票数 0

我试图用布尔值设置一个变量(currentState),但在条件变量中似乎无法识别该变量。我遗漏了什么?

代码语言:javascript
复制
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))"')
    }
}

EN

回答 1

Stack Overflow用户

发布于 2018-06-23 06:48:00

@Barmar谢谢!将"currentState“变量移出,如下所示:

代码语言:javascript
复制
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))"')
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50996260

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档