我正在尝试创建一个包含2行的下拉导航栏。默认情况下,仅显示1行。如果单击此行,则两行都应显示。然后,如果您单击两行之一,则仅应显示该行。等等。这里有几张图像可以证明我希望实现的目标。

这是我要实现的示例,但我希望在没有jQuery的情况下实现。 https://codepen.io/matthewbeta/pen/zioHr

javascript - 更改顺序下拉导航-LMLPHP javascript - 更改顺序下拉导航-LMLPHP javascript - 更改顺序下拉导航-LMLPHP

它已经部分起作用了,但是我无法弄清楚如何仅在单击行B时显示它。现在发生的是,单击行-A,将同时显示两行。如果单击行B,则仅显示行A。



var select = document.getElementById("select");
var rowB = document.getElementById("rowB");
rowB.style.display = "none";

select.addEventListener("click", function(){
  if (rowB.style.display == "none") {
    rowB.style.display = "flex";
  }
  else {rowB.style.display = "none"};
});

body {
  margin: 0px;
}

#content {
  width: 300px;
  height: 300px;
  background: #000;
  display: grid;
  grid-template-rows: 70px 160px 70px;
}

#select {
  width: 270px;
  height: 90px;
  margin: 0 auto;
  color: #fff;
  margin-top: 10px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  z-index: 2;
}

#rowA,
#rowB {
  width: 270px;
  height: 40px;
  background: #000;
  border: #2e2e2e 1px solid;
  display: flex;
  align-items: center;
  z-index: 2;
}

<body>
  <div id="content">
    <div id="select">
      <div id="rowA">Row-A</div>
      <div id="rowB">Row-B</div>
    </div>
  </div>
</body>

最佳答案

仅对js部分进行一些修改:



var select = document.getElementById("select");
var rowB = document.getElementById("rowB");
rowB.style.display = "none";

select.addEventListener("click", function(){
  if(event.target.id === 'rowA') {
    rowB.style.display = (rowB.style.display === 'none')? "block" : "none";
    rowB.style.order = '1';
    rowA.style.order = '0';
  }
  else if(event.target.id === 'rowB') {
    rowA.style.display = (rowA.style.display === 'none')? "block" : "none";
    rowA.style.order = '1';
    rowB.style.order = '0';
  }
});

body {
  margin: 0px;
}

#content {
  width: 300px;
  height: 300px;
  background: #000;
  display: grid;
  grid-template-rows: 70px 160px 70px;
}

#select {
  width: 270px;
  height: 90px;
  margin: 0 auto;
  color: #fff;
  margin-top: 10px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  z-index: 2;
}

#rowA,
#rowB {
  width: 270px;
  height: 40px;
  background: #000;
  border: #2e2e2e 1px solid;
  display: flex;
  align-items: center;
  z-index: 2;
}

<body>
  <div id="content">
    <div id="select">
      <div id="rowA">Row-A</div>
      <div id="rowB">Row-B</div>
    </div>
  </div>
</body>

09-16 22:05