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

如何实现Rocket.Chat首页div内图片随页面滚动移动的效果

问题原因

  • 你当前CSS中给图片设置的transform是固定写死的数值,没有和页面滚动行为做动态绑定,自然不会跟随滚动产生位移变化
  • 缺少滚动监听逻辑,没有计算目标区块在视口中的可见比例,来动态换算图片的偏移量
  • 未给图片预留足够的上下偏移空间:你当前图片容器max-height设为524px,需要保证内部img的高度大于容器高度,才有余量做上下移动而不会露出背景

实现步骤

  1. 先调整SCSS配置,给图片设置足够的高度:
.community {
    position: relative;

    .content-info {
        padding: 110px 140px 64px;
        flex: 1;
        background-color: #f7f8fa;
        background-position: -40px 0;
        background-size: 730px;
        background-repeat: no-repeat;

        div.text {
            margin: 0;
            font-size: 1.6rem;
            line-height: 3.2rem;
        }
        
        .btn-contract-us {
            background-color: #f5455c;
        }
    }

    .content-image {
        overflow: hidden;
        width: 30%;
        max-height: 524px;
        max-width: 430px;
        background-color: #1f2329;
        background-image: linear-gradient(180deg, #1f2329 60%, #000);
        position: relative; /* 新增相对定位 */

        img {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 700px; /* 高度大于容器的524px,预留偏移空间 */
            transform: translate3d(0, 0, 0);
            transform-style: preserve-3d;
            will-change: transform;
        }
    }
}
  1. 给组件增加滚动监听逻辑,动态计算图片偏移量(以你使用的Angular框架为例):
import { Component, HostListener, ElementRef } from '@angular/core';

@Component({
  // 你的原有组件配置
})
export class YourComponent {
  codeImg = '你的图片资源地址';
  constructor(private el: ElementRef) {}

  @HostListener('window:scroll')
  onScroll() {
    const section = this.el.nativeElement.querySelector('.community');
    const img = this.el.nativeElement.querySelector('.content-image img');
    if (!section || !img) return;

    // 获取区块在视口的位置信息
    const rect = section.getBoundingClientRect();
    const viewportHeight = window.innerHeight;
    // 计算区块进入视口的比例 取值范围0~1
    const scrollRatio = Math.max(0, Math.min(1, (viewportHeight - rect.top) / (viewportHeight + rect.height)));
    // 偏移范围:最多往上移176px(700-524),根据滚动比例动态计算
    const offsetY = scrollRatio * -176;
    
    // 用requestAnimationFrame更新保证渲染性能
    requestAnimationFrame(() => {
      img.style.transform = `translate3d(0, ${offsetY}px, 0)`;
    });
  }
}
  1. 后续可以根据实际需求调整偏移范围、滚动比例的计算逻辑,匹配你想要的滚动速度效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 22:24:01