onclick事件需要单击两次,新的flex元素会溢出行

时间:2019-04-21 22:43:18

标签: javascript css flexbox

我在此笔中包含了相关代码:https://codepen.io/whoismikeo/pen/YMvMmR

基本上,我想尝试一个带有按钮的介绍部分,该按钮旁边会显示第二部分(或在移动设备的下方)。

<projectsheader class="row" id="Projects">
<h1>This Is a Title</h1>
</projectsheader>
    <projects>
      <div class="row"> <!--start flex row-->
        <div class="col" id="list-intro"> <!--start intro section-->
          <div class="to-do"> <!--start intro-->
          <h2>Here's a Subtitle</h2>
          <p>And a description!</p>
            <button type="button" 
            class="btn" 
            onclick="addProject();">Create a Flexy</button>
          </div> <!--end intro-->
        </div> <!--end intro section-->
        <div class="col" id="react-list"> <!--start hidden project section-->
          <div class="proj"> <!--start content-->
          <h2>This is Filler</h2>
          <p>A wee little app goes here.</p>
        </div> <!--end content-->
       </div> <!--end hidden project section-->
    </div> <!--end flex row-->
  </projects>

CSS:

projectsheader {
    font-size: 10vh;
    justify-content: center;
    color: #011C43;
    margin-top: 1em;
    font-family: sans-serif;
}

h2, p {
  font-family: sans-serif;
}

.row {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    width: 100%;
}

.col {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    margin: 1em;
    flex-basis: 100%;
    flex: 1;
}

projects .col{
    background-color: rgb(192, 164, 255);
    background-position: center;
    background-size: cover;
    background-repeat: no-repeat;
    text-align: center;
}

projects .row{
    background-color: coral;
    height: 75vh;
    flex-wrap: wrap;
}

.to-do {
    margin: auto;
    padding: 5em;
}

#react-list {
    display: none;
    margin: auto;
    flex-direction: column;
    justify-content: space-around;
    margin: 1em;
    min-width: 50%;
    flex: 2;
}

JS:

function addProject() {
   var target = document.getElementById("react-list");
   if (target.style.display === "none") {
      target.style.display = "flex";
   } else {
      target.style.display = "none";
   }
}

我遇到两个问题:

1)我想不通如何在将flex列包裹行时防止它们从行容器中溢出。

2)切换第二个弹性列的onclick事件首先需要单击两次才能激活。之后,只需一个。

我尝试弄乱不同的行设置以防止列溢出,并且一直在这里寻找双击问题的解决方案,但似乎没有任何效果。

任何帮助都非常感谢!

1 个答案:

答案 0 :(得分:0)

您的JavaScript代码正在检查ID为newFlexItem的元素是否具有display: none样式属性,因此应将此样式属性添加到HTML元素,以使检查逻辑在第一次单击时起作用-它会在第一次单击后起作用,因为您的JS代码将display: none样式属性添加到else块中的元素。

<div class="col" id="newFlexItem" style="display: none">

对于CSS问题,您应该删除height: 100vh,因为这取决于视口的高度。

projects .row {
    background-color: coral;
 /* height: 75vh; */
    flex-wrap: wrap;
}