简体   繁体   English

反应 - 滚动到某个目标元素时应用 CSS class

[英]React - Applying CSS class when scrolled to a certain target element

I am trying to apply a CSS class upon a user scrolling to a particular target element.我正在尝试在用户滚动到特定目标元素时应用 CSS class 。 I've written a helper function here:我在这里写了一个助手 function :

export function isTriggerElementInViewport(elementId) {
    const element = document.getElementById(elementId)
    const rect = element.getBoundingClientRect()

    const viewportWidth = window.innerWidth || document.documentElement.clientWidth
    const viewportHeight = window.innerHeight || document.documentElement.clientHeight

    return (rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= viewportHeight &&
        rect.right <= viewportWidth)
}

And my React component is:我的 React 组件是:

const MyComponent = () => {  
    const [elementVisible, setElementVisible] = useState(false)

    const _handleScroll = elementId => {
        console.log('Scrolling')
        setElementVisible(isTriggerElementInViewport(elementId))
    }

    useEffect(() => {
        window.addEventListener('scroll', () => _handleScroll('targetElementId'))
    }, [])

    return (
        <div className={elementVisible ? 'special-class' : ''} id="targetElementId">
            When this is visible, apply the special CSS class.
        </div>
     )
}

I've written a console log in the handle scroll listener and it does not get called when I scroll.我在句柄滚动侦听器中编写了一个控制台日志,当我滚动时它不会被调用。 To clarify: I am scrolling the window of the page and when I get to a certain element, I want a CSS class to be applied.澄清一下:我正在滚动页面的 window ,当我到达某个元素时,我想要应用 CSS class 。

How do I achieve this behavior?我如何实现这种行为?

Note: I would prefer ideas/solutions that does not involve JQuery or other external libraries as many of the other answers about this tends to do.注意:我更喜欢不涉及 JQuery 或其他外部库的想法/解决方案,因为有关此问题的许多其他答案往往会这样做。

I tried to simluate you in codesandbox: https://codesandbox.io/s/react-playground-forked-5tw7t?file=/index.js:0-1229我试图在代码框中模拟你: https://codesandbox.io/s/react-playground-forked-5tw7t?file=/index.js:0-1229

I don't see any problem with it.我看不出有什么问题。 You can check the console log and inspect at developer tool to see the class is toggled when you scrolled there您可以检查控制台日志并在开发人员工具中检查以查看 class 在您滚动到那里时是否已切换

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM