我确实让我的 div 水平滚动。但它不使用鼠标滚轮滚动。我尝试了“react-scroll-horizontal”包,但它的主体锁定选项对我不起作用,而且它没有轮子选项。另外,我想锁定文档主体滚动,直到 div 完全滚动到末尾。所以我想控制并了解我的div滚动状态。
handleDivScroll = (e) => {
const container = document.getElementsByClassName("labels-box");
console.log(container.scrollTop)
console.log(container.scrollLeft)
}
<div className="labels-box">
{this.handleDivScroll}
<img className="labels" src={LabelImg} alt="" />
<img className="labels" src={LabelImg} alt="" />
<img className="labels" src={LabelImg} alt="" />
<img className="labels" src={LabelImg} alt="" />
</div>
这不能很好地显示控制台消息。
.labels-box {
min-width: 100%;
display: flex;
overflow-x: scroll;
}
这使得 div 水平滚动,但鼠标滚轮不起作用。
另外,我也尝试过
transform: rotate(-90deg); //for .labels-box
transform: rotate(90deg); //for .labels
但是鼠标滚轮不起作用。
最佳答案
您可以使用scrollmagic 来实现这一点。可以看到scrollmagic库Here他们有一个 React 包,您可以使用 npm 或 yarn 安装 Here 。我将我评论的示例推送到了 github,这样你就可以下载存储库并根据你的喜好进行自定义 Here 。这背后的基本思想是将一个部分固定在窗口上,然后在滚动的同时水平移动该部分,直到完成,然后继续正常地向下滚动网站。所以你的组件看起来像下面这样:
import React, { useState } from 'react';
import { Controller, Scene } from 'react-scrollmagic';
import { Tween, Timeline } from 'react-gsap';
const SlideContainer = () => {
const [state] = useState({
sections: [
{ id: 1, imgSrc: 'https://placehold.it/1920x1080' },
{ id: 2, imgSrc: 'https://placehold.it/1920x1080' },
{ id: 3, imgSrc: 'https://placehold.it/1920x1080' },
{ id: 4, imgSrc: 'https://placehold.it/1920x1080' }
]
});
const tweenPercentage = 100 - 100 / state.sections.length;
return (
<Controller>
<Scene triggerHook="onLeave" duration={2000} pin>
{progress => (
<div className="pin-container" style={styles.pinContainer}>
<Timeline totalProgress={progress} paused>
<Tween from={{ x: '0%' }} to={{ x: '-' + tweenPercentage + '%' }}>
<div
className="slide-container"
style={{
...styles.slideContainer,
width: state.sections.length + '00%'
}}
>
{state.sections.map(section => (
<div
className="panel"
key={section.id}
style={styles.panel}
>
<div
style={{
background: 'url(' + section.imgSrc + ')',
backgroundSize: 'cover',
backgroundPosition: 'center',
width: '100%',
height: '100%'
}}
/>
</div>
))}
</div>
</Tween>
</Timeline>
</div>
)}
</Scene>
</Controller>
);
};
const styles = {
normalSection: {
background: '#282c34',
height: '100vh',
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
},
pinContainer: {
height: '100vh',
width: '100%',
overflow: 'hidden'
},
slideContainer: {
height: '100%',
display: 'flex'
},
panel: {
flex: 1,
padding: '40px',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center'
}
};
export default SlideContainer;
在示例中,我只是循环遍历放置在状态中的对象,然后我有一些方程来自动设置 div 宽度,但您可以相当轻松地根据自己的喜好对其进行自定义。将 div 放置在 .slide-container
内,并确保根据您的喜好设置幻灯片容器的宽度。如果您有任何疑问,请告诉我。
关于javascript - 如何通过鼠标滚轮水平滚动div,锁定body滚动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55465239/