仅使用 CSS 关闭模式

Close Modal using CSS only

我需要像这样使用 css 来关闭我的模式:http://jsfiddle.net/raving/1mhsynmw/

但是,我无法让它工作。下面是我的模式。

function alert(msg) {
 document.getElementById("alert").innerHTML = '<div class="modal-overlay"><div class="modal"><div class="modal-container"><h3>' + msg + '</h3><p>' + msg + '</p></div><p class="modal-footer"><a href="javascript:" id="ok">OK</a></p></div>';
}

alert("This is some text to show you this modal. This is some text to show you this modal. This is some text to show you this modal. This is some text to show you this modal.");
body {
  font-family:arial;
  font-size:11px;
}
.modal {
     position: fixed;
     top: 20px;
     margin-left: auto;
     margin-right: auto;
     left: 0;
     right: 0;
     width: 200px;
     box-shadow: 0 4px 6px 1px rgba(50, 50, 50, 0.14);
     background: #fff;
}
.modal p {
  cursor:default;
}
.modal-container {
  padding: 10px;
}
.modal p a {
  color:#555;
}
.modal-footer a {
  display:block;
  border:1px solid #eee;
  width:9.5%;
  padding:3px;
  background:#fff;
  text-decoration:none;
  float:right;
}
.modal-footer {
     background: #fafafa;
     border-top: 1px solid #eee;
     margin-bottom: 0px;
  margin-top:0px;
  padding:8px;
  height:25px;
}
.modal h3 {
  margin:0px;
  white-space: nowrap;
     overflow: hidden;
     text-overflow: ellipsis;
     max-width: 175px;
}
.modal-last {
  padding-bottom:0px;
}
.modal-overlay:before {
     content: '';
     position: fixed;
     top: 0px;
     left: 0px;
     width: 100%;
     height: 100%;
     background: rgba(0, 0, 0, 0.5);
}
<div id="alert"></div>

<h3>Content..</h3>
<p>Just to show it's a modal</p>

问题:有什么方法可以不使用 Javascript 来关闭模式?这是不可能的,我如何使用 Javascript 关闭此模式?

根据您的 js 代码,您将模态元素注入到 dom document.getElementById("alert").innerHTML = 'modal stuff' 中,如果您想摆脱它,最简单的方法是使用这样的空字符串:document.getElementById("alert").innerHTML = ''

CSS 方式类似于 display: none

关闭它的正确方法是调用 javascript 关闭函数,这将删除模态并自行清理(因此旧代码不再存在)。此方法取决于模态的类型和您想要实现的目标。

如果您不想在单击确定按钮时使用 JQuery 关闭模式,您可以使用普通 JavaScript 执行类似于以下代码的操作。您必须为选择器分配一个索引才能使其正常工作。

    //begin click event
    document.getElementById("ok").addEventListener("click",function(event){


    /* Hide the element with a class name of modal.
       note:If there is more than one element with the class name
       modal then this code will only select the first one in the
       collection of elements 
    */

    document.getElementsByClassName("modal")[0].style.display = "none";


       });//end click event

我不相信有 css 唯一的方法可以在单击“确定”按钮后 close/hide 模式。但是,用普通 Javascript 关闭应该很容易。根据您是要隐藏模态(但将其保留在 DOM 中),还是实际删除模态元素,您可以像这样实现它。

 // To hide, run this inside a click callback
 document.getElementById('modal').classList.push('hide');

 .hide {
   display: hidden;
 }



 // And to remove
 var modal = document.getElementById('modal');
 modal.parentNode.removeChild(modal);

此外,您还必须将#modal id 添加到模态框,而不仅仅是class(除非您想使用document.getElementsByClassName)