监听window.onscroll事件
获取上面卷去的距离:document.documentElement.scrollTop
获取左边卷去的距离:document.documentElement.scrollLeft
滚动到指定位置
执行 window.scrollTo(参数) 事件
语法1—传递数字:
window.scrollTop(x,y)
x—表示横向滚动的距离
y—表示纵向滚动的距离
语法2—传递对象:
widow.scrollTop({left:xxx,top:xxx})
或者可以添加behavior属性,属性值为smooth,表示平滑滚动
比如:window.scrollTo({left:10, top: 10, behavior: "smooth" })
例子:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> div { height: 1300px; width: 2000px; background-color: pink; } </style> </head> <body> <button id="btn">点击</button> <div></div> <script> /* 浏览器卷去的尺寸 卷去的高度 document.documentElement.scrollTop 卷去的宽度 document.documentElement.scrollLeft */ // 页面一打开就执行了,滚动条没动就为0 console.log(document.documentElement.scrollTop); //0 //要用onscroll动态获取 //浏览器上面卷去的尺寸 window.onscroll = function () { console.log(document.documentElement.scrollTop); // 浏览器左边卷去的尺寸 // console.log(document.documentElement.scrollLeft); }; //传递数字 // btn.onclick = function () { // window.scrollTo(10, 500); // }; //传递对象 btn.onclick = function () { window.scrollTo({ top: 1000, behavior: "smooth" }); }; </script> </body> </html>