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;:文本颜色恢复为初始值(通常是默认颜色)。

相关推荐
漂流瓶jz11 分钟前
清除浮动/避开margin折叠:前端CSS中BFC的特点与限制
前端·css·面试
涵信9 天前
第一节 布局与盒模型-Flex与Grid布局对比
前端·css
skyymrj9 天前
Vue3 + Tailwind CSS 后台管理系统教程
前端·css·vue
涵信9 天前
2025年CSS最新高频面试题及核心解析
前端·css
welkin9 天前
实现CSS动画中,遇到的几个问题
前端·css
不爱说话郭德纲9 天前
👨‍面试官:你为什么用Less / Scss ?别人用你就用?🤔
前端·css·面试
轻语呢喃10 天前
Stylus初体验:从入门到深入详解
css·stylus
小桥风满袖10 天前
Three.js-硬要自学系列36之专项学习包围盒
前端·css·three.js
编程小明10 天前
scroll-marker实现tab效果
前端·css
LuckySusu10 天前
【CSS篇】CSS 性能优化与代码健壮性提升方法详解
前端·css