js控制滚动条位置并添加过渡效果 您所在的位置:网站首页 js设置动画效果怎么做 js控制滚动条位置并添加过渡效果

js控制滚动条位置并添加过渡效果

2024-06-14 14:18| 来源: 网络整理| 查看: 265

js改变滚动条位置使用scrollTop属性

// 网页可见区域高:document.body.clientHeight // 网页正文全文高:document.body.scrollHeight // 网页可见区域高(包括边框的高):document.body.offsetHeight // 网页被卷去的高:document.body.scrollTop

offsetTop:元素到offsetParent顶部的距离 offsetParent:距离元素最近的一个具有定位的祖宗元素(relative,absolute,fixed),若祖宗都不符合条件,offsetParent为body。如下图所示:获取child的offsetTop,图1的offsetParent为father,图2的offsetParent为body。 在这里插入图片描述

demo

Document .box { width: 500px; height: 500px; border: 1px solid #ccc; margin: 20px auto; overflow: auto; } .box>div { width: 100%; height: 100%; background-color: antiquewhite; } #div2 { background-color: bisque; height: 80%; } #div3 { background-color: coral; } .btn-group { width: 500px; margin: 20px auto; } 1 2 3 按钮1 按钮2 按钮3 let oBox = document.querySelector(".box") let timer; function handleClick(i) { // 网页可见区域高:document.body.clientHeight // 网页正文全文高:document.body.scrollHeight // 网页可见区域高(包括边框的高):document.body.offsetHeight // 网页被卷去的高:document.body.scrollTop // 连续点击先清除定时器 clearInterval(timer) let div = document.querySelector('#div'+i) // 21:如果外层盒子距离浏览器顶部有margin(注意包括盒子的边框) let target = div.offsetTop-21; timer = setInterval(() => { // 步长,速度 let speed = (target - oBox.scrollTop)/5; speed = speed>0?Math.ceil(speed):Math.floor(speed) // console.log(speed) oBox.scrollTop = oBox.scrollTop + speed; // 滚动条是否已经到底: 盒子被卷去的高度+盒子可见区域的高度 = 盒子正文的总高度 let isBottom = (oBox.scrollTop + oBox.clientHeight === oBox.scrollHeight) if(speed==0 || isBottom){ clearInterval(timer) } }, 30); }

参考文章: https://www.jb51.net/article/219621.htm



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有