弹出框也是前端里面经常使用的一个应用场景了,最开始想到的是用js实现这个效果,看到codepen上面有用css实现的。其实就是用到了css里面的一个:target选择器+visibility属性。
URL 带有后面跟有锚名称 #,指向文档内某个具体的元素。这个被链接的元素就是目标元素(target element)。:target 选择器可用于选取当前活动的目标元素。
示例代码:
<div class="container">
<a href="#popup" class="button">删除</a>
<div class="popup" id="popup">
<div class="popup-inner">
<div class="popup__text">
<h3>删除宝贝</h3>
<p>确定要删除该宝贝吗?</p>
<p><span><a href="javascript:void(0)">确定</a></span><span><a href="#">关闭</a></span></p>
</div>
<a href="#" class="popup__close">×</a>
</div>
</div>
</div>
scss代码:
$main-color: #9191E9;
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
html, body {
font-family: 'Raleway', sans-serif;
font-size: 16px;
}
.container {
background-color: $main-color;
display: flex;
align-items: center;
justify-content: center;
100vw;
height: 100vh;
}
.button {
text-decoration: none;
font-size: .875rem;
}
.popup {
display: flex;
align-items: center;
justify-content: center;
position: fixed;
bottom: 0;
right: 0;
100vw;
height: 100vh;
z-index: 2;
visibility: hidden;
&-inner {
background-color: #fff;
400px;
height: 180px;
display: flex;
align-items: center;
position: relative;
bottom: -100vw;
right: -100vh;
transform: rotate(32deg);
transition: .64s ease-in-out;
}
&__text {
padding: 2rem;
h3 {
font-size: 1.2rem;
font-weight: 600;
margin-bottom: 1.2rem;
}
p {
font-size: .75rem;
margin-top: 1rem;
}
span {
display: inline-block;
padding: .42rem 1rem;
margin-right: .625rem;
a {
text-decoration: none;
}
&:first-child {
background-color: #52A0E5;
border: 1px solid #52A0E5;
a {
color: white;
&:hover {
text-decoration: underline;
}
}
}
&:last-child {
border: 1px solid grey;
a {
color: grey;
&:hover {
color: red;
text-decoration:underline;
}
}
}
}
}
&__close {
position: absolute;
right: 1.8rem;
top: 1.8rem;
font-size: 1.5rem;
color: grey;
text-decoration: none;
font-weight: 800;
}
&:target {
visibility: visible;
.popup-inner {
bottom: 0;
right: 0;
transform: rotate(0);
}
}
}
scss代码有点略长,核心就是.popup:target
与visibility
的结合,为什么不用opcaity和display呢?在这个场景中,opacity会影响html页面里的锚(这里面的popup遮挡到了body里面的a标签),而display不支持transition,并使transition失效。这里为了让弹出框不那么突兀地出现,加了一个小小的动画效果。