3 回答
TA贡献1852条经验 获得超7个赞
您将打开和关闭功能都绑定到同一个按钮。所以当你点击它时,浏览器会同时打开和关闭模态框,所以看起来什么也没发生。只需将其绑定到正确的按钮即可。
此外,为模态添加默认状态关闭。
// Get about modal element
var modal = document.getElementById('simpleModal');
// get open about modal link
var aboutModal = document.getElementById('aboutModal');
// Get close button
var closeBtn = document.getElementsByClassName('closeBtn')[0];
// listen for open/close click
aboutModal.addEventListener('click', openModal);
closeBtn.addEventListener('click', closeModal);
// opens and closes modal
function openModal(){
modal.style.display = 'block';
}
function closeModal(){
modal.style.display = 'none';
}
#simpleModal {
display: none;
}
<nav class="navbar">
<div class="logo">
<h4>Earthquake Feed</h4>
</div>
<ul class="nav-links">
<li>
<a href="#simpleModal" data-target="simpleModal" data-toggle ="simpleModal" id="aboutModal">About</a>
</li>
<li>
<a href="#">Legend</a>
</li>
</ul>
</nav>
<!--About Modal-->
<div id="simpleModal" class="modal">
<div class="modal-content">
<span class="closeBtn">×</span>
<p>Hello....I am a modal</p>
</div>
</div>
TA贡献1875条经验 获得超5个赞
您需要添加openModal()到aboutModal和您closeModal的点击处理程序到closeBtn. 通过将这两个都添加到aboutModal这两个都被调用。单击首先aboutModal执行,openModal()然后立即执行closeModal。见片段。
// Get about modal element
var modal = document.getElementById('simpleModal');
// get open about modal link
var aboutModal = document.getElementById('aboutModal');
// Get close button
var closeBtn = document.getElementsByClassName('closeBtn')[0];
// listen for open/close click
aboutModal.addEventListener('click', openModal);
closeBtn.addEventListener('click', closeModal);
// opens and closes modal
function openModal() {
modal.style.display = 'block';
}
function closeModal() {
modal.style.display = 'none';
}
document.addEventListener('DOMContentLoaded', () => {
modal.style.display = 'none'
})
<nav class="navbar">
<div class="logo">
<h4>Earthquake Feed</h4>
</div>
<ul class="nav-links">
<li><a href="#simpleModal" data-target="simpleModal" data-toggle="simpleModal" id="aboutModal">About</a></li>
<li><a href="#">Legend</a></li>
</ul>
</nav>
<!--About Modal-->
<div id="simpleModal" class="modal">
<div class="modal-content">
<span class="closeBtn">×</span>
<p>Hello....I am a modal</p>
</div>
</div>
TA贡献1817条经验 获得超6个赞
您在 上添加了打开和关闭click
事件aboutModal
,因此关闭模态的函数超过了打开模态的函数所做的工作。
您需要closeModal
在closeBtn
.
closeBtn.addEventListener('click', closeModal);
添加回答
举报