如何在我的模态上创建第二个关闭按钮(除了左上角x)

时间:2017-12-25 23:33:22

标签: javascript html css

我想添加另一个"取消"除了用于关闭模态的span选项之外,模态底部的按钮。不知道从哪里开始请告知一些选项。感谢

<!-- The Offer Modal-->
<!-- Trigger/Open The Modal -->
<button id="makeOfferBtn">Make an Offer</button>
<!-- The Offer Modal content -->
<div id="myOfferModal" class="modal">
    <!-- Modal content -->
    <div class="modal-content">
        <span class="close">&times;</span>
    </div>
</div>


<script>
// Get the modal
var modal = document.getElementById('myOfferModal');

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

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

// When the user clicks 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";
    }
}
</script>

1 个答案:

答案 0 :(得分:2)

这是一个快速而肮脏的示例,可以使用定义了.close类的任意数量的按钮:

// Selecting all nodes that are `.close`
var closeBtns = document.querySelectorAll('.close');

// Iterating over on all of them and 
// attaching handlers for the 'click' event. 
for (var i = 0, max = closeBtns.length; i < max; i++) {
    var close = closeBtns[i];
    close.addEventListener('click', function() {
        modal.style.display = 'none';
    });
}

但是,为了不使用这么多全局变量,我建议稍微重新构建一下代码。