作为一个初学者,我试图创建一个模式,一旦点击共享按钮就会显示出来,但我似乎不知道为什么onclick函数没有执行,想法是,一旦点击共享按钮,就会显示:none;将更改为display:block,所以要么style.display=“block”有问题,要么(更有可能的是)我很烂。感谢任何帮助。谢谢你之前。
HTML代码:
<div class="navbar-container">
<div class="nav nav-1" >
<button class="btn btn-1" id="sharebtn">Share </button>
</div>
<div class="nav nav-2">
<button class="btn btn-2" id="howbtn">how does it work ?</button>
</div>
<div class="nav nav-3" >
<button class="btn btn-3" id="abouttns">About</button>
</div>
</div>
<!---Creating the modals-->
<div id="modal-share">
<div class="modal-header">
<button class="close-share">×</button>
</div>
<div class="link">
<input type="text" class="link-input" placeholder="www.youtube.com/jdlkfsjakfdsa">
<button id="share-btn" onclick="fuck">share</button>
</div>
<div class="description">
<input type="text" max="50" placeholder="cats are not that smart">
</div>
</div>
CSS代码:
#modal-share{
display: none; /*hidden by default*/
position: fixed; /*staying in the center even when scrolling*/
z-index: 1; /*stays on top of grids, 3D translation*/
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: white; /*color of the modal*/
background-color: rgba(0,0,0,0.4); /*color of the background*/
border:1px solid black;
}
Javascript代码:
<script>
var modal=document.getElementById("modal-share");
var share_btn=document.getElementsById("sharebtn");
var close_share=document.getElementsByClassName("close-share");
share_btn.onclick=function(){
modal.style.display="block";
}
close_share.onclick=function(){
modal.style.display="none";
}
window.onclick=function(event){
if(event.target==modal){
modal.style.display="none";
}
}
</script>
在您的脚本中实际上存在一个错误,该错误导致了其他所有操作的失败,即
var share_btn=document.getElementsById("sharebtn");
没有函数Document.GetElementsById,只有Document.GetElementById。我有你的代码与以下链接的修复-
https://jsfidle.net/2pfzc4gl/
有两件事,首先,您的代码中有一个输入错误getElementsById
应该是getElementById
。第二个是GetElementsByClassName
返回一个数组(如元素集合),因此您需要从数组中检索第一个元素。下面是更新的JavaScript。
const modal = document.getElementById("modal-share");
const share_btn = document.getElementById("sharebtn"); // typo here in original
const close_share = document.getElementsByClassName("close-share")[0]; // select first element in HTML collection
share_btn.onclick = function() {
modal.style.display="block";
}
close_share.onclick = function() {
modal.style.display="none";
}
window.onclick = function(event) {
if(event.target==modal) {
modal.style.display="none";
}
}