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

如何用img标签替换CSS背景实现随机位置动态图片气泡效果

所需补充的修改内容

你需要补充元素定位、随机属性配置、动画绑定三部分逻辑,具体修改如下:

  • 1. 为每个图片气泡添加基础样式与随机位置、尺寸配置

    所有气泡需要设置绝对定位才能在容器内自由排布,同时生成随机尺寸、坐标避免所有气泡重叠:
    this.el = document.createElement("img");
    this.el.src = src;
    // 新增以下代码
    const randomSize = Math.random() * 70 + 30; // 尺寸范围30-100px,可自定义
    this.el.style.cssText = `
      position: absolute;
      width: ${randomSize}px;
      height: ${randomSize}px;
      border-radius: 50%;
      object-fit: cover;
      left: ${Math.random() * 100}%;
      top: ${Math.random() * 100}%;
      pointer-events: none;
    `;
    bubblesEl.appendChild(this.el);
    
  • 2. 补全上浮动画逻辑

    参考原版效果给每个气泡添加随机时长、随机延迟的浮动动画,首先在CSS中定义动画帧:
    @keyframes floatBubble {
      0% { transform: translateY(0) rotate(0deg); opacity: 0.8; }
      50% { transform: translateY(-100px) rotate(10deg); opacity: 0.5; }
      100% { transform: translateY(0) rotate(0deg); opacity: 0.8; }
    }
    
    然后在JS中给每个图片元素绑定动画:
    // 加在appendChild之前即可
    const animDuration = Math.random() * 4 + 3; // 3-7s随机时长
    const animDelay = Math.random() * 2; // 0-2s随机延迟
    this.el.style.animation = `floatBubble ${animDuration}s ease-in-out ${animDelay}s infinite`;
    
  • 3. 修正列表遍历逻辑

    仅加载第一张图通常是遍历图片URL数组时的作用域问题,确保你是遍历所有传入的地址,每个地址单独生成独立的img实例,示例如下:
    // imgList为你存放所有自定义图片URL的数组
    imgList.forEach(src => {
      // 把创建img、设置样式、添加到容器的逻辑放在forEach内部
      const img = document.createElement("img");
      img.src = src;
      // 上述样式、动画代码写在这里
      bubblesEl.appendChild(img);
    })
    
  • 4. 给容器添加基础样式

    确保气泡的父容器设置了相对定位、溢出隐藏:
    #bubbles-container {
      position: relative;
      width: 100%;
      height: 100%;
      overflow: hidden;
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 09:54:01