请老师看下
来源:2-14 BOM特效开发(1)
我不是胖球球
2021-06-10 11:22:09
相关代码:
<!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>
body {
height: 5000px;
background-image: linear-gradient(to bottom, rgba(65, 65, 235, 0.918), rgb(133, 192, 133), rgb(207, 207, 139));
}
.backtop {
/* 固定定位 */
position: fixed;
bottom: 100px;
right: 100px;
width: 90px;
background-color: #fff;
text-align: center;
padding: 5px;
/* 小手状 */
cursor: pointer;
}
</style>
</head>
<div class="backtop" id="backtopbtn">返回顶部</div>
<script>
var oBacktopbtn = document.getElementById('backtopbtn');
var Timer;
oBacktopbtn.onclick = function () {
// 防止用户不断点击,设表先关
clearInterval(Timer);
// 设置定时器
Timer = setInterval(function () {
// 不断让 scrollTop值减少
document.documentElement.scrollTop -= 200;
// 定时器肯定要停啊?什么时候停呢
if (scrollTop <= 0) {
clearInterval(Timer);
}
}, 20)
}
</script>
<body>
</body>
</html>
问题描述:为什么不可以将scrollTop先赋值,然后直接用呢?这样运行不出结果
相关截图:

1回答
同学你好,可以将scrollTop变量先赋值为document.documentElement.scrollTop,然后再执行scrollTop -= 200,但是要把执行完scrollTop -= 200后的scrollTop值再赋给document.documentElement.scrollTop,页面才会发生滚动,否则只是在不断修改scrollTop变量的值而已,参考代码如下
祝学习愉快!
相似问题