锚点和平滑滚动为html元素提供了以ID为目标的链接
div id='top'/diva href='#top '页面顶部可以使用跳转/a最新的scroll-behavior属性平滑滚动CSS
html { scroll-behavior : smooth; }观察效果
scrollTo、scrollBy和scrollIntoViwe首先向根节点添加scroll-behavior属性,以实现CSS的平滑滚动
html { scroll-behavior : smooth; }然后向按钮添加单击事件,并使用scrollTo、scrollBy或scrollIntoViwe方法滚动到顶部。
Window.scrollTo ()滚动到文档中的坐标。
Elem.scrollTo ()方法将接口滚动到指定元素的指定坐标位置。
window.scroll to (0,0 ) document.documentelement.scroll to (0,0 ) Window.scrollBy ) )以窗口中指定的偏移显示文档
Elem.scrollBy ) )方法使元素滚动特定的距离。
Window.scrollby(0,-100000 ) document.documentelement.scrollby (0,-100000 ) window.scroll )位于文档中的特定位置
Elem.scroll (方法用于滚动到特定元素中的特定坐标。
window.scroll (0,0 ) document.documentelement.scroll ) 0,0 ) elem.scrollintoviwe ) top滚动页面以显示elem
top=true (默认值),页面滚动并在窗口顶部显示Elem。 元素的上边缘与窗口的上边缘对齐。 top=false,页面滚动,Elem显示在窗口底部。 元素的下边缘与窗口的下边缘对齐。 查看document.documentelement.scrollintoview ()效果
检测滚动位置: scroll事件使用document.documentElement返回文档的根元素。 必须获取偏移值,并将click事件侦听器添加到按钮中。 在scrollToTop函数中,使用scrollTo方法滚动到屏幕顶部。 constscrolltotopbtn=document.query selector ('.scrolltotopbtn ' ) const rootelement=document.documentelement conststscrop behavior : ' smooth ' } scrolltotopbtn.addevent listener (click ',scroolltotopbtn.addevent listener ),scrollltototototopbent lent
每当用户滚动时,都会调用handleScroll函数。 这里,需要可以滚动的像素总数。
Element.scrollHeight只读属性。 指定元素内容的高度,包括由于溢出而变得不可见的部分。 Element.clientHeight只读属性。 如果指定元素的内部高度(以像素为单位),则可以看到包含内部页边距的部分的高度,但不包括水平滚动条、边框和外部页边距。 functionhandlescroll ((constscrolltotal=rootelement.scrollheight-rootelement.clientheight if ) ) rootelement.scrooot { scrolltotopbtn.class list.add (show BTN ) }else ) scrolltotopbtn.class list.remove (show BTN ) } document.class list
使用intersectionobserverapintersectionobserverapi,可以异步观察目标元素与祖先元素或顶级文档视口交叉的更改。
与上一次scroll事件侦听滚动相比,Intersection Observer API是解决此类问题的好方法。 这是一个相当新的浏览器API,它允许开发人员以更优化的方式将大多数任务传递给浏览器。
const target=document.query selector (footer ) ) constscrolltotopbtn=document.query selector (.scrollltotopbtn ) ) ) )。 回调将接受entries数组作为参数。 功能呼叫后退(入口, 观察器(entries.foreach ) entry=(if ) entry.isintersecting ) scrolltotopbtn.classlist.add ) ' show BTN ' ' else { const observer=newintersectionobserver ) callback ) observer functionscrolltotop ({ rootelement.scroll to ),behavior :
requestAnimationFrame配置动画window.requestAnimationFrame ()指示浏览器运行动画,并在下次重新绘制之前调用指定的回调函数来更新动画此方法必须将在浏览器下次重新绘制之前执行的回调函数作为参数传递
Element.scrollTop属性获取或设置元素内容在垂直方向滚动的像素数。 使用window.requestAnimationFrame ()设置滚动动画。 const scrollToTop=() constc=document.documentelement.scroll top|| document.body.scroll top if (c0 ) window.)