我在My Next.JS应用中创建了一个Modal,我添加了一个功能,当用户开始滚动到Modal外部时关闭Modal。但是效果也会应用到Modal内部。我怎么能只在滚动到外部而不是内部时关闭呢?
function HomeFilterModal({ visible, onClose }) {
const toggle = useSelector(selectModal);
const dispatch = useDispatch();
const handleOnClose = (e) => {
if (e.target.id === "container") onClose();
};
useEffect(() => {
const handleScroll = () => {
if (window.scrollY >= 10) {
onClose();
}
};
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
}, []);
if (!visible) return null;
return (
<div
id="container"
onClick={handleOnClose}
className="fixed top-24 bottom-0 left-0 right-0 bg-black bg-opacity-30 backdrop-blur-sm h-screen z-50 hidden sm:flex justify-center "
>
<div
id="nonscroll"
className=" h-[28rem] w-2/3 bg-[#fafaf9] drop-shadow-md rounded-3xl flex flex-col items-center overflow-hidden overflow-y-scroll scrollbar-none snap-y
"
>
<div className="flex items-center justify-between w-full px-4 py-4 border-b">
<div
onClick={() => dispatch(setModal(!toggle))}
className=" rounded-full border h-8 w-8 border-gray-600 hover grid place-items-center hover:border-0 hover:drop-shadow-2xl hover:shadow-black"
>
<XMarkIcon className="h-4 w-4" />
</div>
<p className="text-2xl tracking-wider">Filter</p>
<p
onClick={() => dispatch(resetFunc())}
className="text-sm hover:underline pr-2 cursor-pointer"
>
Clear All
</p>
</div>
<HomePriceFilter />
<HomeLocationFilter />
<HomeTypeFilter />
{/* <div className="py-6 h-48 bg-white w-full text-transparent">hey</div> */}
</div>
</div>
);
}
export default HomeFilterModal;
1条答案
按热度按时间at0kjp5o1#
你可以使用
Intersection Observer API
。非常强大和快速:https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API只是假设,因为我没有深入研究您的代码。
创建观察者(如文档所述):
观察父视图(背景):
仅当观察到(背景)移动时触发
close()
。