簡體   English   中英

在 Svelte 中捕獲滾動元素而不是 window

[英]Capture scroll over element instead of window in Svelte

僅當用戶在其上方的元素上啟動向下垂直滾動事件時,如何才能啟用自動滾動到元素的頂部? 我想這樣做,以便頁面頂部的滾動動作啟動平滑滑動並捕捉到用於 UI/UX 目的的下一個重要元素。 我正在使用 Svelte。

<script>
    import Card from './Card.svelte';
    
    const cards = ["card1", "card2", "card3", "card4"]

    let y = 0;
    let lastY = 0;
    let theater;
    let upperContainer;

    const scrollToTheater = (y) => {
        let dy = lastY - y;
        lastY = y;

        if (dy < -10) {
            document.body.parentNode.scrollTo({
                top: theater.offsetTop,
                left: 0,
                behavior: 'smooth'
            })
        }
    }

    $: scrollToTheater(y);

</script>

<svelte:window bind:scrollY={y} />

<main>
    <header>
        <h1>Hello World!</h1>
    </header>
    <div id="upper-container" bind:this="{upperContainer}">
        <h2>Capture scroll over this area only</h2>
    </div>
    <div class="theater" bind:this="{theater}">
        {#each cards as card}
            <Card {card} />
        {/each}
    </div>
    <footer>
        Footer
    </footer>
</main>

<style>

    header {
        width: 100%;
        height: 40px;
        padding:10px 20px 0 0;
    }

    #upper-container {
        width: 100%;
        height: 50vw;
        margin: 30px 0;
        background-color: rebeccapurple;
    }
    
    .theater {
        background-color: black;
        overflow: hidden;
  }

</style>

這是一個REPL 在 REPL 中,您可以看到雖然在滾動到紫色 div 時效果有效,但它會干擾從下方區域滾動。

我已經嘗試通過刪除以替代方式編寫滾動事件偵聽器:

<svelte:window bind:scrollY={y} />

並添加:

<div id="upper-container" bind:this="{upperContainer}" on:scroll={() => {alert("scrolled")}}>

或者:

onMount(() => {
    const upper_container = document.getElementById("upper-container");
    upper_container.addEventListener("scroll", () => alert("scroll"))
});

沒有結果(請參閱 REPL 中注釋掉的塊)。 如果我用“點擊”替換“滾動”,這些事件 function 符合預期。 I also tried using getBoundingClientRect().bottom to test the position of the cursor relative to the element, but when I place upperContainer.getBoundingClientRect().bottom in the scrollToTheater function block, upperContainer is undefined .

滾動事件只有在滾動實際發生時才會觸發。 在您的示例中,您正在尋找滾動的框中沒有足夠的內容來實現這一點。

這是您的REPL ,其中使用 onMount 技術在框中添加了內容並綁定到元素。

這是容器上帶有on:scroll事件處理程序的REPL ,不需要綁定,兩者都可以正常工作。

但是,如果您要跟蹤的是鼠標滾輪在容器上滾動的時間,即使容器內沒有足夠的內容來觸發滾動,那么您將需要使用on:mousewheel處理程序,如下所示REPL的版本,您可能希望也可能不希望在執行此操作時阻止Default,它絕對不考慮移動用戶,但這也有效。

暫無
暫無

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

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