function showTodos(e) {
document.getElementById('modal_todos').style.display = "block";
}
function closeTodoDiv(e) {
document.getElementById('modal_todos').style.display = "none";
}
<div class=" modal modal-todos" id="modal_todos">
<button style="float: right; margin-top:3px;margin-right:8px;">x</button>
<button class="btn btn-secondary btn-sm">Add new Todo</button>
<h2>dfdfdf</h2>
<h2>dfdfdf</h2>
</div>
单击按钮后,我无法关闭弹出的div。虽然showTodos()可以正常工作,但无法理解为什么“ none”不起作用。也是唯一使用的ID。
答案 0 :(得分:0)
您需要使用onclick
属性为按钮附加点击事件。
function showTodos(e) {
document.getElementById('modal_todos').style.display = "block";
}
function closeTodoDiv(e) {
document.getElementById('modal_todos').style.display = "none";
}
* {
margin: 0;
}
.modal {
background-color: #ccc;
}
.o-btn {
position: absolute;
top: 0;
z-index: -1;
}
<div class="modal modal-todos" id="modal_todos">
<!-- added onclick="closeTodoDiv()" -->
<button style="float: right; margin-top:3px;margin-right:8px;" onclick="closeTodoDiv()">x</button>
<button class="btn btn-secondary btn-sm">Add new Todo</button>
<h2>dfdfdf</h2>
<h2>dfdfdf</h2>
</div>
<!-- button to open the modal. added onclick="showTodos()" -->
<button class="o-btn" onclick="showTodos()">open modal</button>
一种现代且更好的方法是使用addEventListener
方法代替内联事件,并存储该模式的引用以提高性能。
const modal = document.getElementById('modal_todos'),
btnOpen = document.getElementById('open'),
btnClose = document.getElementById('close');
btnOpen.addEventListener('click', () => modal.style.display = 'block');
btnClose.addEventListener('click', () => modal.style.display = 'none');
* {
margin: 0;
}
.modal {
background-color: #ccc;
}
.o-btn {
position: absolute;
top: 0;
z-index: -1;
}
<div class="modal modal-todos" id="modal_todos">
<button style="float: right; margin-top:3px;margin-right:8px;" id="close">x</button>
<button class="btn btn-secondary btn-sm">Add new Todo</button>
<h2>dfdfdf</h2>
<h2>dfdfdf</h2>
</div>
<button class="o-btn" id="open">open modal</button>
答案 1 :(得分:0)
您应该在按钮上使用侦听器来使用此逻辑:
const $modalTodos = document.getElementById('modal_todos')
const $btnOpenModal = document.getElementById('btn-open-modal')
const $btnCloseModal = document.getElementById('btn-close-modal')
$btnOpenModal.addEventListener('click', showTodos)
$btnCloseModal.addEventListener('click', closeTodoDiv)
function showTodos() {
$modalTodos.style.display = "block";
}
function closeTodoDiv() {
$modalTodos.style.display = "none";
}
.modal {
display: none
}
<button id="btn-open-modal">open</button>
<div class=" modal modal-todos" id="modal_todos">
<button id="btn-close-modal" style="float: right; margin-top:3px;margin-right:8px;">x</button>
<button class="btn btn-secondary btn-sm">Add new Todo</button>
<h2>dfdfdf</h2>
<h2>dfdfdf</h2>
</div>