前言
今天呢给大家带来css里边的一个技巧哈,与其说是技巧倒不如说是实现功能,这个灵感是我在做老师布置的学院主题网页时突发奇想的一个功能。
左边的是老师要求的样式,而右边则是我的,大家肯定想问内容去哪里了?这才是今天的重头戏,下面来看演示
很帅是吧,如果加入js还可以实现自动弹出效果更佳,但是本人的知识有限所以暂时就不实现了,那我就来分享一下纯css实现这个效果。
一、实现原理
首先需要一个盒子用于装文字和内容,然后用一个盒子把原有的内容盒子覆盖住(这里可以采用伪元素的办法,但是我就分享一下最简单粗暴的办法),当鼠标移动到盒子内时,装有内容的盒子就可以通过动画拉伸展示内容,下面来说说具体步骤吧!
二、代码实现
1、HTML代码
<body>
<!-- 定义上层盒子 -->
<div class="div-x">打开</div>
<!-- 定义下层内容盒子 -->
<div class="div-y">
<dd>你好</dd>
<dd>你好</dd>
<dd>你好</dd>
<dd>你好</dd>
</div>
</body>
2、CSS代码
<style>
/* 覆盖元素 */
.div-x{
width: 100px;
height: 100px;
border-radius: 50%;
font-size: 30px;
font-family: 'Courier New', Courier, monospace;
color: rgb(20, 29, 55);
line-height: 105px;
text-align: center;
background-color: rgb(155, 155, 229);
top: 30px;
left: 30px;
pointer-events: none;/* 关键代码,使这层元素无效,鼠标直接穿透 */
z-index: 2;
position: absolute;
}
/* 动画伸出条 */
.div-y{
width: 70px;
height: 70px;
font-size: 20px;
line-height: 70px;
text-align: center;
background-color: antiquewhite;
/* margin-top: 45px;
margin-left: 38px; */
position: relative;
top: 38px;
left: 36px;
transition: 1.2s;
z-index: 1;
}
.div-y:hover {
position: relative;
transition: 2s;/* 动画优化 */
width: 600px;
}
/* 使文字在没有鼠标移入时不显示 */
.div-y dd{
display: none;
}
.div-y:hover dd{
animation: 3s fade;
display: inline-block;
}
/* 文字延迟显示动画 */
@keyframes fade{
0%{opacity: 0;}
25%{opacity: 0;}
100%{opacity: 1;}
}
</style>
总结
我来简单说一下上面的代码,最主要的是一个层级问题。就是z-index这个属性,如果不设置的话,浏览器会自动按元素排版,就不能实现遮挡功能,当然上面也说了伪元素也可以实现,其次就是动画,我们在hover伪类设置元素的变化时,要用到transition,作为一个变化过程,从而达到美观,然后就是最最重要的pointer-events属性了,设置为none可以穿透上层元素,达到效果,其次呢js也是可以达到这些效果的。后面也会给大家带来其它CSS的小技巧。点个赞支持一下吧!
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Do</title>
</head>
<body>
<div class="div-x">打开</div>
<div class="div-y">
<dd>你好</dd>
<dd>你好</dd>
<dd>你好</dd>
<dd>你好</dd>
</div>
</body>
<style>
/* 覆盖元素 */
.div-x{
width: 100px;
height: 100px;
border-radius: 50%;
font-size: 30px;
font-family: 'Courier New', Courier, monospace;
color: rgb(20, 29, 55);
line-height: 105px;
text-align: center;
background-color: rgb(155, 155, 229);
top: 30px;
left: 30px;
pointer-events: none;
z-index: 2;
position: absolute;
}
/* 动画伸出条 */
.div-y{
width: 70px;
height: 70px;
font-size: 20px;
line-height: 70px;
text-align: center;
background-color: antiquewhite;
/* margin-top: 45px;
margin-left: 38px; */
position: relative;
top: 38px;
left: 36px;
transition: 1.2s;
z-index: 1;
}
.div-y:hover {
position: relative;
transition: 2s;
width: 600px;
}
.div-y dd{
display: none;
}
.div-y:hover dd{
animation: 3s fade;
display: inline-block;
}
@keyframes fade{
0%{opacity: 0;}
25%{opacity: 0;}
100%{opacity: 1;}
}
</style>
</html>