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

实现鼠标悬停时重复背景图单个元素的旋转动画效果

解决单个背景十字悬停旋转的问题

你之前的代码问题在于,transform: rotate是作用在整个.el-section元素上,所以整个元素包括背景图会一起旋转,而不是单个重复的背景单元——因为背景图是元素的一部分,并非独立DOM元素,没法直接对单个背景单元加hover效果。

要实现单个十字悬停旋转,得把每个十字做成独立的DOM元素,再给单个元素加hover动画,具体实现如下:

1. HTML结构

<div class="el-section"></div>

2. CSS样式

.el-section {
  display: grid;
  /* 自动填充列,每列宽度对应十字尺寸 */
  grid-template-columns: repeat(auto-fill, 50px);
  grid-template-rows: repeat(auto-fill, 50px);
  gap: 0; /* 取消间距,让十字无缝重复 */
  width: 100%;
  height: 300px; /* 按需设置容器高度 */
}

.cross {
  width: 50px;
  height: 50px;
  background-image: url("/Untitled-2.svg");
  background-size: cover;
  /* 给旋转加过渡动画 */
  transition: transform 0.3s ease-in-out;
}

.cross:hover {
  transform: rotate(360deg);
  cursor: default;
}

3. JS动态生成十字元素

用JS自动生成对应数量的十字元素,避免手动重复编写:

const section = document.querySelector('.el-section');
// 计算容器内可容纳的行列数
const cols = Math.floor(section.clientWidth / 50);
const rows = Math.floor(section.clientHeight / 50);
const totalItems = cols * rows;

// 批量创建十字元素
for (let i = 0; i < totalItems; i++) {
  const cross = document.createElement('div');
  cross.classList.add('cross');
  section.appendChild(cross);
}

这样每个十字都是独立的DOM元素,鼠标悬停时只会旋转当前指向的十字,移出后自动恢复原状。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 02:27:54