CSS: 回到顶部侧边栏
2022/6/27 23:29:47
本文主要是介绍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>
这篇关于CSS: 回到顶部侧边栏的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-14CSS-Module学习:轻松入门指南
- 2024-11-12CSS9资料入门指南
- 2024-11-12CSS浮动资料详解:初学者指南
- 2024-11-12CSS选择器资料详解与实战教程
- 2024-11-12CSS样式资料:初学者必备指南
- 2024-11-11CSS项目实战:从入门到上手
- 2024-11-11CSS定位项目实战:新手指南
- 2024-11-11CSS浮动项目实战:初学者指南
- 2024-11-11CSS选择器项目实战:从入门到上手
- 2024-11-11CSS样式项目实战:新手入门指南