[英]show and hide button on scroll up and down
please solve it if you can do, I made a function when I scroll down, I can show the "button" {this is basically an arrow which indicates from bottom to top}.如果可以的话请解决它,当我向下滚动时我做了一个 function,我可以显示“按钮”{这基本上是一个从下到上指示的箭头}。 I want to add another function that when I scroll down >500 it will show the button, and if I scroll up it will hide, and if I stop scrolling if my window is scrolled >500 it will show otherwise it will hide.我想添加另一个 function,当我向下滚动 >500 时,它将显示按钮,如果我向上滚动,它将隐藏,如果我停止滚动,如果我的 window 滚动 >500,它将显示,否则它将隐藏。
export default function ScrollToTop() {
const [isVisible, setIsVisible] = useState(false);
const ScrollToTop= () => {
window.scrollTo({
top: 0,
behavior: "smooth"
});
};
useEffect(() => {
// Button is displayed after scrolling for 500 pixels
const toggleVisibility = () => {
if (window.pageYOffset > 500) {
setIsVisible(true);
} else {
setIsVisible(false);
}
};
window.addEventListener("scroll", toggleVisibility);
return () => window.removeEventListener("scroll", toggleVisibility);
}, []);
return (
<div className="scroll-to-top">
{isVisible && (
<div className="top" onClick={scrollToTop}>
<div className="top_img_holder">
<Image src="/uparrow.png" width="16" height="12" alt="" />
</div>
</div>
)}
</div>
)
}
To add the behavior you described, you can try the following:要添加您描述的行为,您可以尝试以下操作:
import { useState, useEffect, useRef } from "react";
export default function ScrollToTop() {
const [isVisible, setIsVisible] = useState(false);
const prevScrollPos = useRef(0);
const scrollToTop = () => {
window.scrollTo({
top: 0,
behavior: "smooth"
});
};
useEffect(() => {
const toggleVisibility = () => {
const currentScrollPos = window.pageYOffset;
// Button is displayed after scrolling for 500 pixels
if (currentScrollPos > 500 && currentScrollPos > prevScrollPos.current) {
setIsVisible(true);
} else {
setIsVisible(false);
}
prevScrollPos.current = currentScrollPos;
};
window.addEventListener("scroll", toggleVisibility);
return () => window.removeEventListener("scroll", toggleVisibility);
}, [isVisible]);
return (
<div className="scroll-to-top">
{isVisible && (
<div className="top" onClick={scrollToTop}>
<div className="top_img_holder">
<Image src="/uparrow.png" width="16" height="12" alt="" />
</div>
</div>
)}
</div>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.