CSS: 回到顶部侧边栏
作者:互联网
<!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> aside { position: absolute; left: 50%; top: 300px; margin-left: 600px; width: 45px; height: 130px; background: aqua; } .w { width: 1200px; margin: 10px auto; } header { height: 150px; background-color: palegreen; } .banner { height: 250px; background-color: plum; } main { height: 1000px; background-color: purple; } span { display: none; position: absolute; bottom: 0; } </style> <script> window.onload = function () { let aside = document.querySelector('aside') let banner = document.querySelector('.banner') let bannerOffsetTop = banner.offsetTop let offset = aside.offsetTop - bannerOffsetTop let main = document.querySelector('main') let goBack = document.querySelector('.go-back') document.addEventListener('scroll', function () { // console.log('banner.offsetTop:', banner.offsetTop) console.log('window.pageYOffset', window.pageYOffset) if(window.pageYOffset > banner.offsetTop) { aside.style.position = 'fixed' aside.style.top = offset + 'px' console.log(1111111111) } else { aside.style.position = 'absolute' aside.style.top = '300px' console.log(222222222222222) } if(window.pageYOffset > main.offsetTop) { goBack.style.display = 'block' } else { goBack.style.display = 'none' } }) goBack.addEventListener('click', function () { // window.scroll({ // top:0,left:0,behavior:'smooth' // }) animate(window, 0) }) } function animate(obj, target, callback) { clearInterval(obj.timer) obj.timer = setInterval(function () { if(target === window.pageYOffset) { clearInterval(obj.timer) callback && callback } let step = (target - window.pageYOffset) / 10 step = step > 0 ? Math.ceil(step) : Math.floor(step) // window.scroll({ // top: 0, left: 0, behavior: 'smooth' // }) window.scroll(0, window.pageYOffset + step) }, 10) } </script> </head> <body> <aside> <span class="go-back">go-back</span> </aside> <header class="w">header</header> <div class="banner w">banner</div> <main class="w">main</main> </body> </html>
标签:pageYOffset,style,顶部,aside,侧边,window,let,banner,CSS 来源: https://www.cnblogs.com/dissipate/p/16415716.html