JavaScript在多个模态上添加类

时间:2017-09-06 00:20:23

标签: javascript html css

我有点绝望。我正在尝试制作与Behance相同的模态,当您点击其中一个小窗口但我无法让我的JavaScript工作。我无法显示“test2”。

function modalActive(){
  document.getElementsByClassName("window")[0].classList.add("modalActive")
};

function closeModal(){
  document.getElementsByClassName("window")[0].classList.remove("modalActive")
};
.gallery-item {
  width: 120px;
  height: 120px;
  border: 3px solid gray;
  float: left;
  margin-left: 10px;
}
.window {
  display: none;
  height: 500px;
  width: 500px;
  Background-color: gray;
  z-index: 100000;
  position: absolute;
  margin: 0 auto;
}
.modalActive {
  display: block !important;
}
<div class="gallery-item">
  <button class="button" onclick="modalActive()">derp</button>
</div>
<div class="window">
  <button class="close" onclick="closeModal()">×</button>
  test1
</div>


<div class="gallery-item">
   <button class="button" onclick="modalActive()">derp</button>
</div>
<div class="window">
  <button class="close">×</button>
  test2 - im not able to see this due to some error in my code/knowledge
</div>

1 个答案:

答案 0 :(得分:0)

单击按钮时,您必须将特定模式定位为打开。目前你只是找到第一个模态并设置modalActive类。

我已更新下面的代码,以便在点击按钮时传递模态ID号。

&#13;
&#13;
function modalActive(id){
  document.getElementsByClassName("window-" + id)[0].classList.add("modalActive")
};

function closeModal(){
  document.getElementsByClassName("modalActive")[0].classList.remove("modalActive")
};
&#13;
.gallery-item {
  width: 120px;
  height: 120px;
  border: 3px solid gray;
  float: left;
  margin-left: 10px;
}
.window {
  display: none;
  height: 500px;
  width: 500px;
  Background-color: gray;
  z-index: 100000;
  position: absolute;
  margin: 0 auto;
}
.modalActive {
  display: block !important;
}
&#13;
<div class="gallery-item">
  <button class="button" onclick="modalActive(1)">derp</button>
</div>
<div class="window window-1">
  <button class="close" onclick="closeModal()">×</button>
  test1
</div>


<div class="gallery-item">
   <button class="button" onclick="modalActive(2)">derp</button>
</div>
<div class="window window-2">
  <button class="close" onclick="closeModal()">×</button>
  test2 - im not able to see this due to some error in my code/knowledge
</div>
&#13;
&#13;
&#13;