尝试使用javascript关闭弹出窗口

时间:2018-10-12 17:55:56

标签: javascript

我是JS新秀,所以请耐心等待。我刚刚使用此代码https://www.w3schools.com/howto/howto_js_popup.asp创建了一个js弹出窗口,现在我试图在右上角添加一个简单的关闭按钮以将用户定向到。我查看了其他一些关闭按钮线程,但它们似乎都没有集成到我的js代码中。

2 个答案:

答案 0 :(得分:0)

i我在网站上搜索了“ js关闭按钮”,它显示了几个线程,但是似乎没有一个简单的添加到js脚本中(我假设那是代码所在的地方)。再次。新手。

答案 1 :(得分:0)

添加一个CSS类,只需单击按钮即可显示并隐藏它

var modal = document.getElementById('myModal');

var btn = document.getElementById("myBtn");

var span = document.getElementsByClassName("close")[0];

btn.onclick = function() {
    modal.style.display = "block";
}

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";
    }
}
body {font-family: Arial, Helvetica, sans-serif;}

/* The Modal (background) */
.modal {
    display: none; 
    position: fixed; 
    z-index: 1; 
    padding-top: 100px; 
    left: 0;
    top: 0;
    width: 100%; 
    height: 100%; 
    overflow: auto; 
    background-color: lightBlue; 
    background-color: grey;
}

   
.modal-content {
    position: relative;
    background-color: #fefefe;
    margin: auto;
    padding: 0;
    border: 1px solid #888;
    width: 80%;
}

.close {
    color: black;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}


.modal-body {padding: 2px 16px;}
<button id="myBtn">Open Modal</button>
<div id="myModal" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">&times;</span>
      <h2>Modal Header</h2>
    </div>
    <div class="modal-body">
      <p>Some text in the Modal Body</p>
      <p>Some other text...</p>
    </div>
    <div class="modal-footer">
      <h3>Modal Footer</h3>
    </div>
  </div>

</div>