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

如何实现悬停触发的带移动小方块的边框过渡动画

实现边框上的橙色小方块滑动动画

我来帮你搞定这个悬停时小方块沿边框移动的效果!核心思路是用CSS伪元素创建橙色小方块,再通过关键帧动画控制它沿着菱形边框的四个角落滑动,具体实现如下:

完整代码修改

CSS 部分

.image-client {
  width: 100%;
  margin: 50px auto;
  display: -webkit-box;
  display: -webkit-flex;
  display: flex;
  flex-wrap: wrap;
}

.image-client-diamond {
  width: 50%;
  padding: 10px;
  margin-bottom: 30%;
  position: relative;
}

.image-client-diamond-inner {
  width: 69.5%;
  height: 0;
  border-radius: 12px;
  border: 2px solid orange;
  padding-bottom: 69.5%;
  /* 移除overflow:hidden,否则小方块会被裁切 */
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%) rotate(45deg);
}

/* 目标元素添加相对定位,作为伪元素的定位基准 */
.hover-image-client {
  position: relative;
}

/* 创建橙色小方块伪元素 */
.hover-image-client::before {
  content: '';
  width: 14px;
  height: 14px;
  background-color: orange;
  position: absolute;
  /* 初始位置在左上角,让小方块一半覆盖边框,一半在外侧 */
  top: -7px;
  left: -7px;
  /* 抵消父元素的45度旋转,保持小方块为正方形 */
  transform: rotate(-45deg);
  /* 默认隐藏,hover时显示并动画 */
  opacity: 0;
  transition: opacity 0.2s ease;
}

/* 悬停时触发动画 */
.hover-image-client:hover::before {
  opacity: 1;
  animation: borderSlide 2s linear infinite;
}

/* 定义小方块滑动的关键帧动画 */
@keyframes borderSlide {
  0% {
    top: -7px;
    left: -7px;
  }
  25% {
    top: -7px;
    left: calc(100% - 7px);
  }
  50% {
    top: calc(100% - 7px);
    left: calc(100% - 7px);
  }
  75% {
    top: calc(100% - 7px);
    left: -7px;
  }
  100% {
    top: -7px;
    left: -7px;
  }
}

img {
  width: 100%;
  transform: rotate(-45deg);
}

HTML 部分(无需修改,保持原结构即可)

<div class="image-client">
  <div class="image-client-diamond">
    <div class="image-client-diamond-inner hover-image-client">
      <img src="http://news.nationalgeographic.com/news/2009/09/photogalleries/new-hubble-camera-first-pictures/images/primary/090909-01-hubble-new-camera-upgraded_big.jpg"/>
    </div>
  </div>
</div>

关键细节解释

  • 移除overflow:hidden:原父元素的溢出隐藏会把边框外的小方块切掉,所以必须去掉才能显示小方块
  • 伪元素旋转抵消:因为父元素是旋转45度的菱形,给伪元素设置rotate(-45deg),让小方块保持正正方形的视觉效果
  • 位置计算:小方块尺寸设为14px,所以top: -7px; left: -7px能让它刚好一半覆盖边框、一半露出外侧,贴合参考图的效果
  • 动画控制:用linear动画曲线保证滑动速度均匀,infinite让动画循环播放,hover时通过opacity控制小方块的显示/隐藏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:42:54