簡體   English   中英

Scroll 上的下一個 Js 模態關閉

[英]Next Js modal close on Scroll

我在我的 Next.JS 應用程序中創建了一個模態框,並且我添加了一個功能來在用戶開始滾動到模態框外時關閉模態框。 但效果也適用於模態內部。 如何僅在向外滾動而不向內滾動時關閉?

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;

您可以使用Intersection Observer API 非常強大和快速: https ://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

只是假設,因為我沒有深入研究您的代碼。

創建一個觀察者(如文檔所述):

let observer = new IntersectionObserver(callback, options);

觀察您的父視圖(背景):

let target = document.querySelector('#yourParentSelector');
observer.observe(target);

僅當觀察到(背景)移動時才觸發您的close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM