首页 > 解决方案 > 从 JS 代码设置为 0 时,CSS flex 属性没有正确响应

问题描述

这可能是我对某些事情的一个非常简单的疏忽,但到目前为止,我有一个非常简单的项目,它将屏幕分为三个部分,前两个部分在一个容器中,display: flex 并且它们都被赋予相同的 flex 值1. 在我的 JS 代码中,当一个特定的布尔变量设置为 false 时,我希望这两个部分中的一个被隐藏,而另一个占据它的位置。如果我在 CSS 中设置 'flex: 0',这将按预期工作,但在 JS 中设置时则不然。

// Init on page load
window.addEventListener("load", function() {
    var gameContainer = document.getElementById("game-container");
    if (!false) { //this is to be changed later on to check for a boolean value
      gameContainer.style.flex = "0"; //this should hide the right part, but it does not
    }
});
#whole-game {
  display: flex;
}

#story-container {
  background-color: black;
  height: 80vh;
  flex: 1;
}

#game-container {
  background-color: blue;
  height: 80vh;
  flex: 1;
}

#settings-container {
  background-color: rgb(83, 50, 8);
  width: 100vw;
  height: 20vh;
}
<body>
  <div id="whole-game">
    <div id="story-container"></div>

    <div id="game-container"></div>
  </div>

  <div id="settings-container"></div>
</body>

这就是我的屏幕在运行代码时的样子

这就是我想要的样子

标签: javascripthtmlcssflexbox

解决方案


正如我在您的代码中看到的,您已将“gameManager”变量声明为数组而不是对象。所以,如果要执行“试用”函数,首先需要访问数组中的对象索引,然后函数:

var gameManager = [{
},

    {trial: function (){
        
      var gameContainer = document.getElementById("game-container");
      if(!false){ //this is to be changed later on to check for a boolean value
        gameContainer.style.flex = "0"; //this should hide the right part, but it does not
      }},
    
}]
// Init on page load
window.addEventListener("load", gameManager[1].trial);

当然,您要将 index [1] 更改为对象的实际索引。


推荐阅读