简体   繁体   English

在特定高度时出现滚动顶部按钮

[英]Scroll top button appear when at a certain height

here's my issue:这是我的问题:

My button ( button used to scroll to the top of the page ) must appear when my window is at the top of my "nav", here is the 2 method i tried, please tell me what i do wrong:当我的 window 位于我的“导航”顶部时,我的按钮(用于滚动到页面顶部的按钮)必须出现,这是我尝试的 2 种方法,请告诉我我做错了什么:

function retourTop(){
    let boutonScroll = document.querySelector("#btnScroll");
    let navbar = document.querySelector("header nav");
    
    
    
    if(document.body.scrollTop < navbar.getBoundingClientRect.y){
        boutonScroll.style.display = "block";
    }else{
        boutonScroll.style.display = "none";
    }

and the second:第二个:

function retourTop(){
    let boutonScroll = document.querySelector("#btnScroll");
    let navbar = document.querySelector("header nav");
    
    if(document.body.scrollTop < document.querySelector("header nav").getBoundingClientRect.y){
        boutonScroll.style.display = "block";
    }else{
        boutonScroll.style.display = "none";
    }
}

I used element.offsetTop and window.scrollY (run code snippet)我使用了 element.offsetTop 和 window.scrollY (运行代码片段)

 let button = document.querySelector("button"); let nav = document.querySelector("nav"); function toggle(display) { button.style.display = display; } window.addEventListener('scroll',function(e) { let navHeight = nav.offsetTop; let scrollHeight = window.scrollY; scrollHeight >= navHeight? toggle("block"): toggle("none"); }); function back() { window.scrollTo(0,0); }
 header { height: 200px; display: flex; background: lightgray; flex-direction: column; justify-content: flex-end; } nav { width: 100%; height: 50px; background: gray; display: flex; flex-direction: column; justify-content: center; text-align: center; } div { height: 200vh; width: 100%; } button { position: fixed; bottom: 0; display: none; }
 <header> <nav>Scroll Down</nav> </header> <div></div> <button onclick="back()">Back to Top</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM