[英]How can I horizontally scroll div by mouse wheel, locking the body scroll?
我确实使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库,并且它们具有一个react软件包,可以使用npm或yarn 在此处安装。 我把我评论到GitHub上的例子,所以你可以下载存储库和定制自己的喜好在这里 。 这背后的基本思想是将一个部分固定到窗口,然后在滚动直到完成为止的同时水平移动该部分,然后继续沿该位置正常滚动。 因此,您的组件将类似于以下内容:
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
,并确保根据自己的喜好设置幻灯片容器的宽度。 如果您有任何问题,请通知我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.