Css和JS实现下划线动效的方法示例

Viola ·
更新时间:2024-09-20
· 692 次阅读

本文主要讲述两种下划线动效效果,第一种悬停时 X轴由内向外展开实现动画效果,第二种为左右自动展示,由左向右,或由右向左!!

实现的主要效果是利用伪类标签,以及hover,利用transfromm trition实现动画效果

x轴由内向外展开

利用贝塞尔曲线利用横线的动画实现,具体代码如下:

ul { display: flex; padding: 0; margin: 0; list-style-type: none; } ul:hover li:not(:hover) a { opacity: 0.2; } ul li { position: relative; padding: 30px 25px 30px 25px; cursor: pointer; } ul li::after { position: absolute; content: ""; top: 100%; left: 0; width: 100%; height: 2px; background: #3498db; transform: scaleX(0); transition: 0.4s cubic-bezier(0.165, 0.84, 0.44, 1); } ul li:hover::after, ul li.active::after { transform: scaleX(1); }

左右横移下划线动画特效

主要利用js判断鼠标移开时的位置,对动画效果的进行左右移入移出显示
 

js代码如下:

document.querySelectorAll('a').forEach(elem => { elem.onmouseenter = elem.onmouseleave = e => { const tolerance = 5; const left = 0; const right = elem.clientWidth; let x = e.pageX - elem.offsetLeft; if (x - tolerance < left) x = left; if (x + tolerance > right) x = right; elem.style.setProperty('--x', `${x}px`); }; });

css 利用伪类标签进行动画效果的动画实现
css代码如下:

a { position: relative; font-weight: 600; text-decoration: none; color: rgba(0, 0, 0, 0.4); transition: color .3s ease; } a::after { --scale: 0; content: ''; position: absolute; left: 0; right: 0; top: 100%; height: 3px; background: #4c81c9; -webkit-transform: scaleX(var(--scale)); transform: scaleX(var(--scale)); -webkit-transform-origin: var(--x) 50%; transform-origin: var(--x) 50%; transition: -webkit-transform 0.3s cubic-bezier(0.535, 0.05, 0.355, 1); transition: transform 0.3s cubic-bezier(0.535, 0.05, 0.355, 1); transition: transform 0.3s cubic-bezier(0.535, 0.05, 0.355, 1), -webkit-transform 0.3s cubic-bezier(0.535, 0.05, 0.355, 1); } a:hover { color: #4c81c9; } a:hover::after { --scale: 1; }



方法 动效 下划线 js CSS js实现 css和js 示例

需要 登录 后方可回复, 如果你还没有账号请 注册新账号