我正在尝试使用布尔值设置变量(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))"')
}
}
答案 0 :(得分:0)
@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))"')
}
}