You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为单一卡片实现多方向Hover过渡效果?

实现单卡片多方向Hover过渡效果

要实现单个卡片支持从任意方向进入/离开时的对应过渡效果,核心是通过JS判断鼠标交互的方向,再配合CSS的渐变和过渡属性完成动画。以下是完整实现方案:

核心逻辑

  • 监听卡片的mouseenter和mouseleave事件,计算鼠标相对于卡片的位置,判断进入/离开方向(上、下、左、右)
  • 根据方向给卡片添加临时类,CSS通过类选择器触发对应方向的背景渐变位移
  • 利用CSS过渡动画,实现覆盖层的展开/收起效果

完整代码

HTML

<div class="container">
  <div class="card">
    <span>多方向Hover卡片</span>
  </div>
</div>

CSS

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  background-color: #15151e;
}

.container {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.card {
  border: 2px solid white;
  height: 120px;
  width: 280px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
  position: relative;
  overflow: hidden;
  transition: background-position 0.5s ease;
}

/* 基础渐变配置,覆盖层占50%,透明占50% */
.card.from-left,
.card.from-right {
  background: linear-gradient(90deg, transparent 50%, #27eba7 50%);
  background-size: 200% 100%;
}

.card.from-top,
.card.from-bottom {
  background: linear-gradient(180deg, transparent 50%, #27eba7 50%);
  background-size: 100% 200%;
}

/* 进入时的位置 */
.card.from-left:hover {
  background-position: 100% 0;
}

.card.from-right:hover {
  background-position: -100% 0;
}

.card.from-top:hover {
  background-position: 0 100%;
}

.card.from-bottom:hover {
  background-position: 0 -100%;
}

JavaScript

const card = document.querySelector('.card');

// 判断鼠标进入/离开方向的函数
function getDirection(element, event) {
  const rect = element.getBoundingClientRect();
  // 计算鼠标相对于卡片中心的位置
  const x = event.clientX - rect.left - rect.width / 2;
  const y = event.clientY - rect.top - rect.height / 2;
  // 根据角度判断方向
  const angle = Math.atan2(y, x) * 180 / Math.PI;
  return (Math.round((angle + 180) / 90) + 3) % 4;
}

card.addEventListener('mouseenter', (e) => {
  const direction = getDirection(card, e);
  // 移除所有方向类,避免冲突
  card.classList.remove('from-left', 'from-right', 'from-top', 'from-bottom');
  // 根据方向添加对应类
  switch(direction) {
    case 0: card.classList.add('from-top'); break;
    case 1: card.classList.add('from-right'); break;
    case 2: card.classList.add('from-bottom'); break;
    case 3: card.classList.add('from-left'); break;
  }
});

card.addEventListener('mouseleave', (e) => {
  // 移除hover状态,触发反向过渡
  card.blur();
});

代码说明

  1. 方向判断函数:通过计算鼠标相对于卡片中心的坐标和角度,确定进入/离开的方向(0=上,1=右,2=下,3=左)
  2. CSS渐变设置:针对水平和垂直方向分别定义渐变,背景尺寸设为200%,通过改变background-position实现覆盖层的滑动
  3. 事件监听:鼠标进入时添加对应方向类,触发展开动画;离开时移除hover状态,CSS过渡会自动执行反向收起动画

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 01:25:37