本章和大家分享的是模拟淘宝右侧导航栏的一个小功能。
左侧是商品内容,右侧是一个导航栏,当页面向下滚动的时候右侧导航栏也跟着移动
当黄色内容区域到达顶部的时候,右侧导航栏变为固定的
当黑色内容区到达顶部时,右侧导航栏的返回顶部按钮显示
点击返回顶部内容区回到原来的位置,右侧导航栏也取消固定回到原来的位置。
具体实现:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style> .slider_bar{ position: absolute; width: 70px; height: 20px; border: 1px solid red; top: 500px; right: 0; } span{ display: flex; border: 1px solid red; } .goBack{ display: none; } .non{ width: 500px; height: 200px; border: 1px solid red; } .header{ width: 500px; height: 200px; background-color: aqua; margin-top: 0; } .banner{ width: 500px; height: 500px; background-color: bisque; } .main{ width: 500px; height: 1000px; background-color: black; } </style> </head> <body> <div class="slider_bar"> <span class="yi">1</span> <span class="er">2</span> <span class="san">3</span> <span class="goBack">返回顶部</span> </div> <div class="non"></div> <div class="header"></div> <div class="banner"></div> <div class="main"></div> <script> var yi = document.querySelector('.yi'); var er = document.querySelector('.er'); var san = document.querySelector('.san'); var sliderbar = document.querySelector('.slider_bar'); var banner = document.querySelector('.banner'); var bannerTop = banner.offsetTop; var sliderbarTop = sliderbar.offsetTop - bannerTop; var main = document.querySelector('.main'); var goBack = document.querySelector('.goBack'); var mainTOP = main.offsetTop; console.log(sliderbarTop); document.addEventListener('scroll', function(){ if(window.pageYOffset >= bannerTop) { sliderbar.style.position = 'fixed'; sliderbar.style.top = sliderbarTop + 'px'; } else { sliderbar.style.position = 'absolute'; sliderbar.style.top = '500px'; }; if(window.pageYOffset >= mainTOP){ goBack.style.display = 'block'; } else { goBack.style.display = 'none'; }; }); goBack.addEventListener('click', function(){ window.scroll(0,0); }) </script> </body> </html>