且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

javascript 模态框实现 -- :target 伪元素实现

更新时间:2022-08-13 10:38:02

上一篇文章中介绍了,使用原生 dialog 的方式实现模态框,这一篇文章简单介绍使用 :target 伪元素的形式实现模态框:
javascript 模态框实现 -- :target 伪元素实现

使用 :target 伪元素方式实现对话框,只能是作为对于 :target 伪元素的了解,其实实际中几乎没用,所以这里不做详细介绍,直接上代码
  1. HTML 标签
<!-- 必须使用 a 标签且 href 里 # 后面的内容,必须是下方 div 的 id -->
<a href="#targetDialog">打开对话框</a>

<div id="targetDialog" class="target-dialog">
    <div class="target-dialog-main">
        <div class="target-dialog-header">
          <span>对话框标题</span>
          <a href="#">X</a>
        </div>
        <div class="target-dialog-container">这是对话框内容</div>
    </div>
</div>
重点:必须使用 a 标签且 href 属性里 # 后面的值必须与下面的 divid 一致。
  1. CSS
.target-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  z-index: 30;
  display: flex;
  justify-content: center;
  align-items: center;
}

.target-dialog-main {
  background-color: white;
  width: 300px;
  border-radius: 5px;
}

.target-dialog-header {
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.target-dialog-container {
  padding: 10px;
  border-top: 1px solid #dedede;
}
#targetDialog {
  display: none;
}
#targetDialog:target {
  display: flex;
}

就以上简单的代码就能实现简单的模态框的效果。