大家好,又见面了,我是你们的朋友全栈君。
html:
(index.html)
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>鼠标悬停下划线</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<nav>
<a href="#">首页</a>
<a href="#">产品展示</a>
<a href="#">新闻资讯</a>
<a href="#">关于我们</a>
</nav>
<script src="js/index.js"></script>
</body>
</html>
css3:
(style.css)
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background: #f8f8f8;
font: normal 400 130%/1.5 -apple-system, BlinkMacSystemFont, Helvetica, Arial, sans-serif;
}
nav {
display: grid;
grid-auto-flow: column;
grid-gap: 1em;
}
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代码段:
(index.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`);
};
});
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/145981.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...