鼠标悬停下划线显示特效,html鼠标悬停显示下划线

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u014789708/article/details/94572918

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`);

  };

});

 

展开阅读全文

没有更多推荐了,返回首页