CSS学习 01 利用鼠标悬停制造文本隐藏效果

效果:
  • 在正常状态下,剧透内容的背景色和文本颜色都是黑色,导致剧透内容看起来是隐藏的(黑色文本在黑色背景上不可见)。
  • 当鼠标悬停在剧透内容上时,背景色和文本颜色恢复为初始值,使得剧透内容可见。


如何实现以上展示的效果呢?

以下HTML代码包含三个帖子,每个帖子都有一个剧透部分。

html 复制代码
<!doctype html>
<html>
    <head>
        <title></title>
        <link rel="stylesheet" href="index.css">
    </head>
    <body>
        <div class="post">
            <p>In the 1968 film Planet of the Apes, they find  
                <span class="spoiler">the ruins 
                    of the Statue of Liberty. The Plant of the
                    Apes is Earth!</span>
            </p>
        </div>
        <div class="post">
            <p>Soylent Green  
                <span class="spoiler">is made of people!</span>
            </p>
        </div>
        <div class="post">
            <p>OMG I can't believe that Darth Vadar is 
                <span class="spoiler">Luke Skywalker's father!</span>
            </p>
        </div>
    </body>
</html>

这些剧透部分被包含在 <span class="spoiler"> 标签中。

css 复制代码
:root {
    --spoiler-color: #000;
}

p {
    line-height: 1.5em;
} 

.post {
    background: #e8eaed;
    padding: 1em;
    border-radius: 1em;
    margin-bottom: 1em;
}

.spoiler {
    background: var(--spoiler-color);
    color: var(--spoiler-color);
    transition: all .5s ease-in;
}

.spoiler:hover {
    background: initial;
    color: initial;
}
  1. 全局变量定义:

:root:表示文档的根元素。定义了一个CSS变量--spoiler-color,值为#000(黑色)。

  1. 段落样式:

p:针对所有<p>标签。
line-height: 1.5em;:设置行高为1.5倍的字高。

  1. 剧透内容样式:

.spoiler:针对所有类名为spoiler的元素。
background: var(--spoiler-color);:背景色使用定义的变量--spoiler-color(黑色)。
color: var(--spoiler-color);:文本颜色使用同一个变量--spoiler-color(黑色),导致文本不可见。
transition: all .5s ease-in;:所有样式变化在0.5秒内以ease-in的效果过渡。

  1. 剧透内容的悬停效果:

.spoiler:hover:当鼠标悬停在类名为spoiler的元素上时。
background: initial;:背景色恢复为初始值(无背景色)。
color: initial;:文本颜色恢复为初始值(通常是默认颜色)。

相关推荐
燕落南枝8 小时前
CSS 表单选择器与伪元素选择器详解
前端·css
狮子座的男孩1 天前
html+css基础:25、3D变换(3D空间与景深/透视点的位置/位移/旋转/缩放/多重变换/背部可见性)
css·经验分享·html·旋转·透视点·缩放/位移·3d变换/空间与景深
思码梁田1 天前
CSS 浏览器厂商前缀:从「写 5 遍」到现代自动化兼容
前端·css·css3·border-radius·1024程序员节·box-shadow·厂商前缀
feixing_fx2 天前
CSS Grid 入门:二维布局时代的降维打击
前端·css·前端框架·css3
2603_965896622 天前
CSS BEM 命名规范|组件化样式分层权威指南
前端·javascript·css
进击的明明2 天前
前端开发中的 BEM 国际命名规范:让 CSS 不再"打架"
前端·css·html
燕落南枝2 天前
CSS 分组选择器与链接伪类选择器详解
前端·css
溪语流沙2 天前
【每天一个CSS | Day33】聚焦即弹出的命令面板
前端·css·html5·组件·每日一练
燕落南枝2 天前
CSS 用户行为伪类::hover 与 :focus 详解
前端·css
钱栈up3 天前
前端改了三页、后端也动了,用户说「完全没变化」——我在 116 库上找到的三个真凶
css·数据库