react、vue、jq页面滚动到指定元素-锚点

相对普通a标签的锚点跳转,没缓动效果,太生硬
推荐使用scrollIntoView()方法

最常见使用方式:

  const scrollToEle = (ele) => {
    let getEle = document.getElementById(ele);
    getEle && getEle.scrollIntoView({ behavior: 'smooth' });//建议判断元素是否存在 再执行滚动
  };

  //若页面(盒子)无法滚动,设置下页面(盒子)可滚动!
  //若无法滚动到页面最底端或最顶端,审查元素布局

调用:scrollToEle( 元素id )

参数说明

参数参数说明备注
behavior“auto”, “smooth”,"instant"之一。默认为 “auto”定义动画过渡效果一般用“smooth”
block“start”, “center”, “end”, 或 "nearest"之一,默认为 “start”定义垂直方向的对齐一般用不到
inline“start”, “center”, “end”, 或 "nearest"之一。默认为 “nearest”定义水平方向的对齐一般用不到

调用:

ele.scrollIntoView({behavior: "instant", block: "end", inline: "nearest"})

浏览器兼容性

在这里插入图片描述
参考文档:
https://developer.mozilla.org/zh-CN/docs/web/api/element/scrollintoview

Logo

前往低代码交流专区

更多推荐