[英]React - Applying CSS class when scrolled to a certain target element
我正在嘗試在用戶滾動到特定目標元素時應用 CSS class 。 我在這里寫了一個助手 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)
}
我的 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>
)
}
我在句柄滾動偵聽器中編寫了一個控制台日志,當我滾動時它不會被調用。 澄清一下:我正在滾動頁面的 window ,當我到達某個元素時,我想要應用 CSS class 。
我如何實現這種行為?
注意:我更喜歡不涉及 JQuery 或其他外部庫的想法/解決方案,因為有關此問題的許多其他答案往往會這樣做。
我試圖在代碼框中模擬你: https://codesandbox.io/s/react-playground-forked-5tw7t?file=/index.js:0-1229
我看不出有什么問題。 您可以檢查控制台日志並在開發人員工具中檢查以查看 class 在您滾動到那里時是否已切換
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.