Css、JS實現下劃線動效

本文主要講述兩種下劃線動效效果,第一種懸停時 X軸由內向外展開實現動畫效果,第二種爲左右自動展現,由左向右,或由右向左!!css

實現的主要效果是利用僞類標籤,以及hover,利用transfromm trition實現動畫效果web

x軸由內向外展開flex

M)YQ{ZDQ]IZ]@[H5(LMUGEK.png

利用貝塞爾曲線利用橫線的動畫實現,具體代碼以下:動畫

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

左右橫移下劃線動畫特效spa

OZGFLNYKPK]@CZIL~]_D(5Y.png

主要利用js判斷鼠標移開時的位置,對動畫效果的進行左右移入移出顯示
js代碼以下:code

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代碼以下:orm

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;
}
相關文章
相關標籤/搜索