You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现CSS文本随滑动背景局部变色,优化hover过渡流畅度

实现背景滑动时仅覆盖区域文本变色的导航效果

可以通过伪元素复制文本并配合宽度动画来实现需求,具体代码如下:

CSS 代码

a.nav {
    font-family: Manrope;
    font-weight: 400;
    text-decoration: none;
    color: #000;
    position: relative;
    display: inline-block;
}

a.nav::before {
    content: attr(data-text);
    position: absolute;
    top: 0;
    left: 0;
    color: #fff;
    background-color: #000;
    width: 0;
    overflow: hidden;
    transition: width .15s;
}

a.nav:hover::before {
    width: 100%;
}

HTML 代码

<a class="nav" data-text="About us">About us</a>

原理说明

利用伪元素::before通过attr(data-text)复制导航的文本内容,将伪元素的文字设为白色、背景设为黑色,初始状态下宽度为0且隐藏溢出内容。当鼠标hover时,伪元素的宽度平滑过渡到100%,这样黑色背景滑动覆盖的区域,对应的白色文本会同步显示,未被覆盖的区域仍显示原黑色文本,实现流畅的局部变色效果。

内容的提问来源于stack exchange,提问作者Tyler Delmas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 22:50:02