You need to enable JavaScript to run this app. 如何实现链接背景跟随鼠标进入方向上下滑入的光标跟随动画效果
优惠活动
大模型
产品
解决方案
定价
更多

如何实现链接背景跟随鼠标进入方向上下滑入的光标跟随动画效果

问题原因

  1. 过渡属性、渐变样式都写在了动态添加的from-top/from-bottom类中,只有鼠标移入加类时才会加载这些配置,动画缺少初始状态做参照,无法触发过渡效果
  2. 两个方向类仅定义了静态背景位置,没有设置位置变化的前后差值,加类后直接跳到最终显示状态,没有动画过程
  3. 渐变方向与背景位置的对应逻辑错误,导致顶部滑入效果没有正确的位移路径

修改方案

CSS代码调整

将公共的过渡、渐变、背景大小配置抽离到元素基类,提前设置好初始透明状态,动态类仅控制背景位置的最终值即可:

.list__item {
  border: 1px solid red;
  display: flex;
  width: 300px;
  padding: 10px;
  cursor: pointer;
  /* 提前配置公共背景和过渡属性 */
  transition: background-position .2s ease;
  background: linear-gradient(red 50%, transparent 50%);
  background-size: 100% 200%;
  /* 初始状态红色完全在可视区域外,显示透明 */
  background-position: 0 100%;
}

/* 从上到下滑入:背景上移,红色从顶部进入 */
.from-top {
  background-position: 0 0;
}

/* 从下到上滑入:背景下移,红色从底部进入 */
.from-bottom {
  background-position: 0 -100%;
}

JS代码调整

将mouseover替换为mouseenter避免子元素冒泡触发重复事件,加类前先移除另一个方向的类避免样式冲突:

const list = document.querySelectorAll('.list__item');
list.forEach(item => {
   item.addEventListener('mouseenter', (evt) => {
     // offsetY小于10视为从顶部进入,其余视为从底部进入
     if (evt.offsetY < 10) {
       item.classList.remove('from-bottom');
       item.classList.add('from-top');
     } else {
       item.classList.remove('from-top');
       item.classList.add('from-bottom');
     }
   });
  item.addEventListener('mouseleave', () => {
    // 移除类自动回到初始透明状态,触发滑出动画
    item.classList.remove('from-top');
    item.classList.remove('from-bottom');
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 19:33:04