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

如何设置仅在落地页顶部固定、滚动页面时不跟随移动的背景?

实现方案

1. 纯HTML/CSS 实现方案

给落地页的根容器加专属类名,通过CSS的背景固定属性实现效果,其他页面不引用该类即可避免背景生效。

<!-- 仅落地页的body/根容器加专属类 -->
<body class="landing-page">
  <div class="content">
    <!-- 页面内容,滚动时会从背景上方划过 -->
  </div>
</body>
/* 仅落地页生效的背景配置 */
.landing-page {
  margin: 0;
  min-height: 100vh;
  background-image: url('你的背景图本地路径/资源地址');
  background-size: cover;
  background-position: top center;
  background-repeat: no-repeat;
  /* 核心属性:背景固定不跟随滚动移动 */
  background-attachment: fixed;
}

/* 内容区域设置透明,保证下层背景可见 */
.content {
  background: transparent;
  min-height: 200vh; /* 可根据实际内容调整,保证滚动效果可触发 */
  padding: 20px;
}

2. 单页应用(SPA)适配方案

如果是React/Vue等单页应用场景,只需要在落地页组件的生命周期钩子中处理类名的新增和移除即可,避免影响其他路由页面。

  • React示例
import { useEffect } from 'react';

const LandingPage = () => {
  useEffect(() => {
    document.body.classList.add('landing-page');
    // 组件卸载时移除类,保证其他页面无该背景
    return () => document.body.classList.remove('landing-page');
  }, []);

  return <div className="content">{/* 落地页内容 */}</div>
}
  • Vue示例
<script setup>
import { onMounted, onUnmounted } from 'vue';

onMounted(() => {
  document.body.classList.add('landing-page')
})
onUnmounted(() => {
  document.body.classList.remove('landing-page')
})
</script>

<template>
  <div class="content"><!-- 落地页内容 --></div>
</template>

移动端兼容优化

如果出现背景随滚动抖动的问题,可以改用fixed定位的伪元素实现,性能和兼容性更好:

.landing-page::before {
  content: '';
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('你的背景图路径');
  background-size: cover;
  background-position: top center;
  z-index: -1; /* 放置在最底层,内容在其上方渲染 */
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 02:48:01