簡體   English   中英

使用 React 到達頁面的特定部分時,如何在滾動時水平移動文本?

[英]How to move text horizontally as you scroll when getting to a specific part of the page with React?

我的頁面中間有兩行文本,我希望它們從頁面外部水平滾動以進入頁面,然后從另一側離開。 最上面的一個來自左邊,通過右邊存在,第二行則相反。 我的問題是,當您更改屏幕大小時,scrollY 不會保持不變。

當您到達頁面的特定部分時,是否有一個很好的解決方案來滾動文本? 現在,該部分在全視圖中顯示為 2200px,我正在使用該數字來觸發滾動

我有這個監聽滾動的鈎子:

export default function useScrollListener() {
    const [data, setData] = useState({
        x: 0,
        y: 0,
        lastX: 0,
        lastY: 0
     });

    // set up event listeners
    useEffect(() => {
        const handleScroll = () => {
           setData((last) => {
               return {
                   x: window.scrollX,
                   y: window.scrollY,
                   lastX: last.x,
                   lastY: last.y
                };
            });
        };

    handleScroll();
    window.addEventListener("scroll", handleScroll);

    return () => {
        window.removeEventListener("scroll", handleScroll);
        };
    }, []);

    return data;
}

在包含兩行的頁面中:

const scroll = useScrollListener();
const [position, setPosition] = useState('')

useEffect(() => {
    let pos = scroll.y
    let scrollPos = pos - 3000
     
    // Section with the lines of text starts around 2200 on scrollY
    if(scroll.y > 2200){
        setPosition(scrollPos.toString())
    }
}, [scroll.y]);

文本環繞在相對的 div 周圍,文本具有 position 絕對值,將元素向右或向左推 800 像素。

<div className="line1">
    <p className="text1" style={{"left": `${position}px`}}>
         Lorem ipsum dolor sit amet.
    </p>
</div>
 
<div className="line2">
    <p className="text1" style={{"right": `${position}px`}}>
         Lorem ipsum dolor sit amet.
    </p>
</div>

修復它的一種快速方法是在樣式 html 中根據它與頁面頂部的距離來計算它。

因此,例如,如果文本相距 100vh 且相距 10vh。

<div className="line1">
    <p className="text1" style={{"left": `calc(100vh - ${position}px`)}}>
         Lorem ipsum dolor sit amet.
    </p>
</div>
 
<div className="line2" style={{marginTop: "10vh"}}>
    <p className="text1" style={{"right": `calc(110vh - ${position}px`}}>
         Lorem ipsum dolor sit amet.
    </p>
</div>

我沒有運行它,對於運行代碼時出現的任何錯誤深表歉意。

暫無
暫無

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

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