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

如何用jQuery和CSS实现左图随右侧文本滚动固定定位?

嘿,这个左图右文的滚动交互需求我之前帮不少人实现过,用jQuery+CSS就能完美搞定,我给你拆成一步步来,好理解又好上手~

一、先搭好基础结构

首先得把HTML的骨架搭起来,一个容器包裹左侧图片和右侧文本:

<div class="container">
  <div class="left-image">
    <img src="your-image-path.jpg" alt="主题图片">
  </div>
  <div class="right-content">
    <!-- 这里放你的长文本内容,比如多篇段落 -->
    <p>这里是第一段文本内容...</p>
    <p>第二段文本,要足够长才能触发滚动效果...</p>
    <!-- 多复制几段让内容能撑出滚动空间 -->
  </div>
</div>
二、基础CSS布局

先把左右分栏的布局搞定,同时给后续的定位打好基础:

/* 容器居中,用flex实现左右分栏 */
.container {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  position: relative; /* 给绝对定位的图片做参照 */
  min-height: 100vh; /* 保证容器至少占满一屏高度 */
}

/* 左侧图片容器 */
.left-image {
  width: 30%;
  position: relative;
  top: 0;
}
.left-image img {
  width: 100%;
  display: block; /* 去掉图片默认的底部间隙 */
}

/* 右侧文本容器 */
.right-content {
  width: 70%;
  padding-left: 40px; /* 给图片和文本之间留点间距 */
}
三、核心:jQuery滚动监听逻辑

这部分是实现交互的关键,我们需要监听页面滚动,判断当前滚动位置,动态给图片切换定位状态:

$(document).ready(function() {
  // 提前获取需要操作的元素和关键尺寸,避免每次滚动都重新计算
  const $imageContainer = $('.left-image');
  const $textContent = $('.right-content');
  const textTop = $textContent.offset().top; // 文本顶部到页面顶部的距离
  const textBottom = textTop + $textContent.outerHeight(); // 文本底部到页面顶部的距离
  const imageHeight = $imageContainer.outerHeight(); // 图片容器的高度
  const fixedTopGap = 20; // 图片固定时距离顶部的间距,可按需调整

  // 监听滚动事件,加防抖避免频繁触发
  let scrollTimer;
  $(window).scroll(function() {
    clearTimeout(scrollTimer);
    scrollTimer = setTimeout(function() {
      const currentScroll = $(window).scrollTop();
      // 计算图片需要固定到文本底部的阈值
      const bottomTrigger = textBottom - imageHeight - fixedTopGap;

      if (currentScroll >= textTop && currentScroll <= bottomTrigger) {
        // 滚动过程中:图片固定在顶部
        $imageContainer.addClass('fixed').removeClass('absolute');
      } else if (currentScroll > bottomTrigger) {
        // 文本滚完了:图片固定在文本底部位置
        $imageContainer.addClass('absolute').removeClass('fixed');
      } else {
        // 回到初始位置:移除所有定位类
        $imageContainer.removeClass('fixed absolute');
      }
    }, 20); // 20ms防抖延迟,兼顾流畅性和性能
  });
});
四、补充定位类的CSS

刚才的jQuery会给图片容器添加fixed和absolute类,我们需要给这两个类写样式:

/* 图片固定时的样式 */
.left-image.fixed {
  position: fixed;
  top: 20px; /* 和上面的fixedTopGap对应 */
  left: calc((100% - 1200px)/2); /* 和容器的max-width对应,保证图片和初始位置对齐 */
  width: 30%; /* 保持和初始宽度一致 */
}

/* 图片固定在文本底部时的样式 */
.left-image.absolute {
  position: absolute;
  bottom: 0;
  top: auto;
  left: calc((100% - 1200px)/2); /* 同样保证对齐 */
  width: 30%;
}
几个注意事项
  • 如果你的页面有固定导航栏,记得把fixed类的top值加上导航栏的高度,避免图片被导航挡住
  • 调整calc((100% - 1200px)/2)里的1200px为你容器的实际最大宽度,确保图片始终和布局对齐
  • 防抖函数是可选但推荐的,能减少滚动时的性能消耗,让页面更流畅

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 16:57:57