总结VUE控制滚动滑动方法

本文介绍了一位开发者改进Vue应用滚动性能的方法,通过自定义函数实现更流畅的滚动效果,适合提升用户体验。分享了scrollToY、scrollToTop、scrollToId和scrollToElement等实用滚动控制函数及其用法。

前景

由于VUE使用虚拟dom,导致滚动条滑动到具体元素非常生硬,在github上看到一位作者写了不错的方法因此记载下来分享

作者地址

传送们
作者的地址

代码

/*
 * y: the y coordinate to scroll, 0 = top
 * duration: scroll duration in milliseconds; default is 0 (no transition)
 * element: the html element that should be scrolled ; default is the main scrolling element
 */
function scrollToY (y, duration = 0, element = document.scrollingElement) {
  // cancel if already on target position
  if (element.scrollTop === y) return;

  const cosParameter = (element.scrollTop - y) / 2;
  let scrollCount = 0, oldTimestamp = null;

  function step (newTimestamp) {
    if (oldTimestamp !== null) {
      // if duration is 0 scrollCount will be Infinity
      scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
      if (scrollCount >= Math.PI) return element.scrollTop = y;
      element.scrollTop = cosParameter + y + cosParameter * Math.cos(scrollCount);
    }
    oldTimestamp = newTimestamp;
    window.requestAnimationFrame(step);
  }
  window.requestAnimationFrame(step);
}

/*
 * duration: scroll duration in milliseconds; default is 0 (no transition)
 * this function is using the scrollToY function
 */
function scrollToTop(duration = 0) {
  scrollToY(0, duration, document.scrollingElement);
}

/*
 * id: the id of the element as a string that should be scrolled to
 * duration: scroll duration in milliseconds; default is 0 (no transition)
 * this function is using the scrollToY function on the main scrolling element
 */
function scrollToId(id, duration = 0, customOffset = 0) {
  const offset = Math.round(document.getElementById(id).getBoundingClientRect().top);
	scrollToY(document.scrollingElement.scrollTop + offset + customOffset, duration);
}

/*
 * element: the node object that should be scrolled to
 * duration: scroll duration in milliseconds; default is 0 (no transition)
 * this function is using the scrollToY function on the main scrolling element
 */
function scrollToElement(element, duration = 0, customOffset = 0) {
	const offset = Math.round(element.getBoundingClientRect().top);
	scrollToY(document.scrollingElement.scrollTop + offset + customOffset, duration);
}
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值