配对显示:flex with display:block and display:none

时间:2017-06-28 15:23:55

标签: javascript css flexbox

我正在使用纯JS和flexbox为我的项目创建网格。

项目的某些部分在页面加载时隐藏了display:none,但在点击按钮后,它应该在display none和block之间切换。

可悲的是,这完全是废墟显示:弯曲或不切换。有没有办法让这两个属性协同工作?

这是JSfiddle我把它放在一起 https://jsfiddle.net/c3dw0woa/

<div class="container">
<div>Text hello I was hidden</div>
</div>

<button class="dis_legend">Click to display</button>

CSS

.container{
 display: flex;
}

JS

var container = document.querySelector('.container');
container.style.display = "none";

var legend_button = document.querySelector('.dis_legend');

var container_displayed = false;
container.style.display = "none";

legend_button.onmousedown = function(){
if(legend_displayed == false){
    container.style.display = "block";
    container_displayed = true;
} else {
    container_displayed.display = "none";
    container_displayed = false;
}
} 

2 个答案:

答案 0 :(得分:2)

你总是在js中使用display= flex来避免问题

我在您的javascript代码中更改了一些内容

查看结果:

var container = document.querySelector('.container');
var legend_button = document.querySelector('.dis_legend');

var container_displayed = false;
container.style.display = "none";

legend_button.onmousedown = function() {
  if (container_displayed == false) {
    container.style.display = "flex";
    container_displayed = true;
  } else {
    container.style.display = "none";
    container_displayed = false;
  }
}
.container {
  display: flex;
}
<div class="container">
  <div>Text hello I was hidden</div>
</div>

<button class="dis_legend">Click to display</button>

答案 1 :(得分:1)

Chiller的解决方案应该可行,但如果您想要使用事件监听器,这是另一种选择:

var container = document.querySelector('.container');
container.style.display = "none";

var legend_button = document.querySelector('.dis_legend');

var container_displayed = false;
container.style.display = "none";

legend_button.addEventListener('click', function(){
        if (container.style.display == "none"){
        container.style.display = "block";
            } else {
      container.style.display = "none";
      }
})