移动端吸顶后页面滚动,导航也随之变化定位的组件 大家有推荐的吗?

如题, 经常碰到一些活动页面, 在移动端 通过监听onscroll去实现效果, 在android手机上性能良好, 但在ios中就显得有些卡顿,并且无法捕捉惯性滑动.

试着用 better-scroll 去写, 但是better-scroll用了css3属性, 子dom fixed 效果不生效,所有放弃了..

大家有推荐的插件吗?

阅读 2.7k
1 个回答

IOS卡顿,节流了解一下.

scroll事件是高频事件,而读取滚动高度又会触发重排重绘,所以才有性能问题.

你可以控制scroll回调调用的频率,也就是节流.

惯性滚动不触发scroll事件也可以用类似的思路解决.滚动结束(并没有这个事件,但可以用防抖函数模拟)后开启定时器检查滚动高度有无变化,有变化则调用scroll回调,并再次设置定时器检查,直到滚动高度不再变化.


测试IOS惯性滚动可以出发scroll事件啊


写都写了,贴上来吧

 // region helpers
  function throttle(fn, gapTime = 16) {
    let _lastTime = null;

    return function () {
      let _nowTime = +new Date();
      if (_nowTime - _lastTime > gapTime || !_lastTime) {
        fn();
        _lastTime = _nowTime;
      }
    };
  }

  const debounce = (fn, time = 100) => {
    let timer = 0;
    return function () {
      const context = this;
      let args = arguments;
      clearTimeout(timer);
      timer = window.setTimeout(() => {
        fn.apply(context, args);
      }, time);
    };
  };

  // endregion

  let scrollTop = 0;

  function scrollHandler(e) {
    console.log('scroll');
    scrollTop = document.scrollingElement.scrollTop;
  }

  function scrollEnd() {
    console.log('scrollEnd');
    checkTop();
  }

  function checkTop() {
    setTimeout(() => {
      if (document.scrollingElement.scrollTop !== scrollTop) {
        console.log('still scroll');
        scrollHandler();
        checkTop();
      }
    }, 300);
  }

  const throttleScroll = throttle(scrollHandler, 300);
  const onScrollEnd = debounce(scrollEnd, 300);

// 测试发现IOS惯性滚动可以触发scroll事件,所以用touchmove替代
  window.addEventListener('touchmove', e => {
    throttleScroll();
    onScrollEnd();
  });

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题