确定尝试使用此脚本完成模式...
<script type="text/javascript">
var modal = document.querySelector('.slicknav_nav');
// Get the button that opens the modal
var btn = document.querySelector(".slicknav_btn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("butinco")[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";
}
}
</script>
这是HTML ...
<div id="slick-mobile-menu">
<div class="slicknav_menu">
<a href="#" aria-haspopup="true" role="button" tabindex="0" class="slicknav_btn slicknav_collapsed" style="outline: none;">
<span class="slicknav_menutxt">Menu</span><span class="slicknav_icon"><span class="slicknav_icon-bar"></span><span class="slicknav_icon-bar"></span>
<ul class="slicknav_nav slicknav_hidden" style="touch-action: pan-y; display: none;" aria-hidden="true" role="menu">
<li class="menu-item"></li>
</ul>
</div>
</div>
结果是:
Cannot set property 'onclick' of null
该如何解决?
当我写作时所有内容都在页面中跳跃时,很难键入或格式化问题。
答案 0 :(得分:0)
您的元素可能尚未准备好。确保在页面完全加载后添加事件侦听器。
document.addEventListener("DOMContentLoaded", function(event) {
// add your document.querySelector here, along with the rest of the code.
});
我也建议使用点击处理程序。
addEventListener('click' , function() { });
代替,因此您拥有更多控制权。