效果
代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Scroll To Top</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
height: 200vh;
}
div.to-top {
position: fixed;
right: 50px;
bottom: 50px;
width: 50px;
height: 50px;
border: 1px solid #000000;
}
div.to-top.hidden {
display: none;
}
p {
padding: 10px;
}
</style>
</head>
<body>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<div class="to-top"></div>
<script type="text/javascript">
window.onload = (event) => {
// console.log(event)
main()
}
function main() {
const divToTop = document.querySelector("div.to-top")
divToTop.classList.toggle("hidden", window.scrollY === 0)
window.onscroll = (event) => {
console.log(window.scrollY)
divToTop.classList.toggle("hidden", window.scrollY === 0)
}
divToTop.onclick = (event) => {
window.scrollTo({ top: 0, left: 0, behavior: 'smooth' })
}
}
</script>
</body>
</html>
参考
Web technology for developers > CSS: Cascading Style Sheets > position
Web technology for developers > CSS: Cascading Style Sheets > border
Web technology for developers > Web APIs > Element > Element.classList
Web technology for developers > Web APIs > DOMTokenList > DOMTokenList.toggle()
Web technology for developers > Web APIs > GlobalEventHandlers > GlobalEventHandlers.onscroll
Web technology for developers > Web APIs > Window > Window.scrollTo()