javascript - 轮播,当父元素垂直滚动移动时让水平滚动结束移动
问题描述
我创建了一个类似于 Instagram 上正在运行的轮播,但我意识到如果我在子元素的滚动 x 移动结束之前移动父元素的滚动 y,它不会结束。
下面的例子的 gif ...
注意:抱歉英语不好,不是我的母语。
代码
.container {
width: 100%;
display: flex;
flex-direction: column;
overflow-y: scroll;
.x {
margin-top: 30px;
display: flex;
overflow-x: scroll;
scroll-snap-type: x mandatory;
div {
flex: 0 0 auto;
scroll-snap-align: start;
width: 100vw;
height: 100vw;
}
.x-item1 {
background: green;
}
.x-item2 {
background: blue;
}
}
}
<Container>
<div className="x">
<div className="x-item1" />
<div className="x-item2" />
</div>
... other divs
</Container>
解决方案
我找到了一个解决方案,在我看来,它可以满足我的建议,而不会失去功能的性能......
我只是认为scrollIntoView可能会有延迟,比如“行为:平滑”......
https://developer.mozilla.org/pt-BR/docs/Web/API/Element/scrollIntoView
但是如果有人想添加改进,它就不起作用了,谢谢。
在容器中我放了一个“onTouchStart”
<Container className="works" onTouchStart={() => handleCarousel()} >
<div className="x">
<div className="x-item1" />
<div className="x-item2" />
</div>
... other divs
</Container>
函数句柄轮播...
const handleCarousel = () => {
const works = Array.from(document.querySelectorAll('.work-content'));
const carousels = Array.from(document.querySelectorAll('.work-carousel'));
carousels.forEach(carousel => {
if (carousel.scrollLeft % window.innerWidth !== 0) {
const item = document.querySelector(
`.work-content:nth-child(${
works.indexOf(carousel.parentElement) + 1
}) > div.work-carousel > img.work-carousel-item-active`,
); // in another function I already control which image is being viewed and add this class
const scroll = document.querySelector('.works').scrollTop; // optional: get vertical scroll value
item.scrollIntoView(); // horizontal scrolling gains focus
document.querySelector('.works').scrollTop = scroll; // optional: returns vertical scroll value
}
});
};
推荐阅读
- mysql - 我应该如何对 CMS 进行 dockerize,这样 MySQL 才能与 git 很好地配合使用?
- shell - 具有不同行大小的多个文件的标准差
- php - 显示没有托管库存的 WooCommerce 变体的“库存”通知
- python - 查询配置单元数据库后,impala dbapi python3 thriftpy2 hiveserver2 无法从游标读取
- mongodb - 是否可以在 mongo db 验证中使用 if then 条件?
- xcode - iPhone 不适用于 IOS 13.6 和 XCode 11.5。请重新连接设备
- c++ - 作为 std::map 键的唯一结构不插入所有数据
- c - 我们可以互换 C 中的 for 循环参数吗?
- reactjs - 使用反应钩子比较 prevstate 和 current state
- node.js - 我可以在 NodeJs 中使用 Sharp 直接处理缓冲区数据吗