使用几种不同的模态

时间:2017-02-22 13:36:34

标签: javascript html css

我跟着this guide用javascript创建一个好看的CSS模式。在我的页面上,我总共需要8种不同的模态。是否可以使用相同的ID等?我知道我必须在Javascript中修复一些内容,但我不知道如何。我现在看到的唯一方法是使用唯一的ID,只需复制Javascript并将变量更改为ID。

但必须有更好的方法,不是吗?这样我就可以做到:

<a id="myBtn" class="modalBtn">Button one</a>
<div id="myModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <span class="close">&times;</span>
            <h2>Button one header</h2>
        </div>
        <div class="modal-body">
            <p>Button one text</p>
        </div>
    </div>
</div>

<a id="myBtn" class="modalBtn">Button two</a>
<div id="myModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <span class="close">&times;</span>
            <h2>Button two header</h2>
        </div>
        <div class="modal-body">
            <p>Button two text</p>
        </div>
    </div>
</div>

让他们正确显示。而不是这样做:

<a id="myBtn1" class="modalBtn">Button one</a>
<div id="myModal1" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <span class="close">&times;</span>
            <h2>Button one header</h2>
        </div>
        <div class="modal-body">
            <p>Button one text</p>
        </div>
    </div>
</div>

<a id="myBtn2" class="modalBtn">Button two</a>
<div id="myModal2" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <span class="close">&times;</span>
            <h2>Button two header</h2>
        </div>
        <div class="modal-body">
            <p>Button two text</p>
        </div>
    </div>
</div>

如果我按第二个例子做的话;然后我必须复制Javascript,使每个按钮和每个模态有8个变量。必须有一种更简单,更清洁的方法。

任何人都知道如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

有趣的是,Id必须是独一无二的。 如果你担心javascript,你可以封装你的函数已经把id作为参数。 即 -

function ModalFunction(modalId, btnId){
  // Get the modal
  var modal = document.getElementById(modalId);

  // Get the button that opens the modal
  var btn = document.getElementById(btnId);

  // Get the <span> element that closes the modal
  var span = document.getElementsByClassName("close")[0];

  // When the user clicks on the button, open the modal 
  btn.onclick = function() {
      modal.style.display = "block";
  }

  // When the user clicks on <span> (x), close the modal
  span.onclick = function() {
      modal.style.display = "none";
  }

  // When the user clicks anywhere outside of the modal, close it
  window.onclick = function(event) {
      if (event.target == modal) {
          modal.style.display = "none";
      }
  }
}

然后像这样调用它:

ModalFunction("myModal1", "myBtn1");
ModalFunction("myModal2", "myBtn2");

你可以在这里找到一个有效的jsfiddle(有一些额外内容) - https://jsfiddle.net/Lcmffb2b/2/