返回顶部的 js 实现方法
- 设置 scrollTo(x,y)中的 x 和 y 的坐标值来滚动到页面的具体位置
<body>
<!-- 返回按钮 -->
<button id="btn">返回顶部</button>
<!-- 内容区 -->
<div class="content"></div>
<script>
var btn = document.querySelector("#btn");
btn.style.display = "none";
var Y = 0;
window.onscroll = function () {
Y = scrollY;
if (Y > 400) {
btn.style.display = "block";
} else {
btn.style.display = "none";
}
};
var content = document.querySelector(".content");
for (var i = 0; i < 100; i++) {
var h1 = document.createElement("h1");
h1.innerHTML = "易烊千玺yyds" + i;
content.appendChild(h1);
}
btn.onclick = function () {
var move = scrollY;
var timer = setInterval(function () {
move -= 10;
if (move <= 0) {
move = 0;
scrollTo(0, move);
clearInterval(timer);
}
scrollTo(0, move);
}, 0.1);
};
</script>
</body>