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

如何使用locomotive库在智能手机端禁用sticky元素吸附效果

移动端禁用Locomotive Scroll Sticky吸附效果解决方案

方案1:CSS媒体查询(最便捷,无需修改JS逻辑)

直接在项目样式表中添加以下代码,在指定移动端尺寸阈值下覆盖Locomotive动态生成的sticky样式即可:

/* 可根据业务需求自行调整移动端判断阈值,常用阈值为768px、992px */
@media (max-width: 768px) {
  #sticky1 {
    position: static !important;
    transform: none !important;
    top: auto !important;
    left: auto !important;
    width: auto !important;
  }
}

该方案通过!important强制覆盖Locomotive添加的内联sticky样式,不需要修改原有初始化逻辑,适合不需要动态切换sticky状态的场景。


方案2:JS动态控制属性(符合Locomotive设计规范,支持动态切换)

Locomotive Scroll通过识别元素上的data-scroll-sticky属性启用sticky效果,你可以在初始化前判断屏幕尺寸,动态控制该属性是否存在:

  1. 先删掉HTML中#sticky1元素上写死的data-scroll-sticky属性
  2. 调整JS初始化逻辑如下:
const mobileThreshold = 768 // 移动端阈值可自行调整
const stickyEl = document.querySelector('#sticky1')
const isMobile = window.innerWidth < mobileThreshold

// 非移动端才添加sticky属性
if (!isMobile) {
  stickyEl.setAttribute('data-scroll-sticky', '')
}

// 原有Locomotive初始化逻辑保持不变
const locoScroll = new LocomotiveScroll({
  el: document.querySelector(".locomotive-scroll"),
  smooth: true,
  smartphone: {
      smooth: true
  },
  tablet: {
      smooth: true
  },
  smoothMobile: 1,
  multiplier: 1.0,
}); 

// 如果需要支持窗口大小变化时动态切换sticky状态,可以增加以下监听
window.addEventListener('resize', () => {
  const nowIsMobile = window.innerWidth < mobileThreshold
  if (nowIsMobile) {
    stickyEl.removeAttribute('data-scroll-sticky')
  } else {
    stickyEl.setAttribute('data-scroll-sticky', '')
  }
  // 通知Locomotive刷新元素状态
  locoScroll.update()
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 11:24:05