js實現用按鈕控制網頁滾動、以及固定導航欄效果


實現效果如下:

在這里插入圖片描述
頁面內有三個按鈕,分別控制頁面向上、向下移動,以及暫停,並設置有導航欄,在滾動到某一位置時顯示。且當用戶主動控制鼠標滑輪時,滾動效果自動關閉。本頁面只是演示如何實現,進行了簡單的布局,沒有過多的美化。代碼如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>網頁滾動效果</title>
    <style> * { margin: 0; padding: 0; } .container { width: 80%; margin: 0 auto; } .nav { width: 100%; height: 200px; background-color: yellow; } .top { width: 100%; height: 400px; background-color: red; } .content1, .content2 { width: 100%; height: 600px; background-color: blue; } .bottom { width: 100%; height: 200px; background-color: green; } .flower { display: none; width: 100%; height: 50px; background-color: black; position: fixed; top: 0; opacity: 0.5; } .up, .down, .remove { display: inline-block; font-size: 40px; line-height: 50px; text-align: center; width: 50px; height: 50px; background-color: white; border: 1px solid #333333; border-radius: 50%; cursor: pointer; position: fixed; right: 40px; } .up:hover { background-color: #eaeaea; } .down:hover { background-color: #eaeaea; } .remove:hover { background-color: #eaeaea; } .up { bottom: 200px; } .down { bottom: 80px; } .remove { font-size: 25px; bottom: 140px; } </style>
</head>
<body>
<div class="container">
    <div class="nav"></div>
    <div class="top"></div>
    <div class="content1"></div>
    <div class="content2"></div>
    <div class="bottom"></div>
</div>
<div class="flower"></div>
<span class="up"></span>
<span class="remove"></span>
<span class="down"></span>
</body>
</html>
<script> let up = document.querySelector('.up'); let down = document.querySelector('.down'); let remove = document.querySelector('.remove'); let flower = document.querySelector('.flower'); let nav = document.querySelector('.nav'); let timer = null; //定時器 let flag = false; //控制定時器 let speed = 10; //控制滾動速度,數值越小越快 document.addEventListener('scroll', function () { if (window.pageYOffset >= nav.offsetHeight) { flower.style.display = 'block'; } else { flower.style.display = 'none'; } }); document.addEventListener('mousewheel', function () { stop(); }) up.addEventListener('click', startUp); down.addEventListener('click', startDown); remove.addEventListener('click', stop); function startUp() { stop(); if (flag) { timer = setInterval(function () { document.documentElement.scrollTop--; }, speed); } flag = !flag; } function startDown() { stop(); if (flag) { timer = setInterval(function () { document.documentElement.scrollTop++; }, speed); } flag = !flag; } function stop() { clearInterval(timer); flag = true; } </script>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM