我的项目遇到麻烦了。我正在尝试使用 Javascript 和 GSAP 创建水平滚动,但前提是宽度 > 1200px。我做了一件事,它有点有效,但如果我将网页大小调整为较小的宽度,它仍然会进行水平滚动。对不起我的英语,请帮助我!!!
const aboutContainer = document.querySelector(".about__container");
const aboutContent = gsap.utils.toArray(".about__container .about__content");
const aboutMask = document.querySelector(".about__mask");
if (document.body.clientWidth > 1200) {
let scrollTween = () => {
gsap.to(aboutContent, {
xPercent: -100 * (aboutContent.length - 1),
ease: "none",
scrollTrigger: {
trigger: ".about__container",
pin: true,
scrub: 1,
end: "+=3000",
},
});
gsap.to(aboutMask, {
width: "100%",
scrollTrigger: {
trigger: ".about__section",
start: "top left",
scrub: 1,
},
});
let tl = gsap.timeline({
scrollTrigger: {
trigger: ".about__container",
start: "center bottom",
},
});
tl.from(aboutContent, { x: 300, opacity: 0, duration: 1 });
};
scrollTween();
};
通常,您可以使用 CSS 媒体查询以更简单的方式实现这一点。
如果你希望滚动仅在设备宽度> 1200px时发生,我假设溢出仅从那时起存在,所以这个简单的CSS将实现你的目标。
.container {
/*set containers width to match window/device width*/
width: 100%;
/*initially hide horizontal overflow in case it exists,*/
/*since inherently do not want horizontal scrolling*/
overflow-x: hidden;
}
@media only screen and (min-width: 1200px){
/*if device's width is >=1200px*/
.container {
/*prevents line breaks -> avoids wrapping*/
/*so that children do not move down*/
white-space: nowrap;
overflow-x: scroll; /*activate scroll*/
}
<div class="container">
<div>
This is a child element
</div>
</div>
我不认为你可以在这里调整输出窗口的大小,所以我做了一个 jsFiddle 这样你就可以看到它的运行情况(我可能是错的,但只是为了确定)。
我使用了 Lorem Ipsum 文本来模拟溢出。在这里,我删除了它,以避免在我的答案中不必要地滚动,因为无论如何调整大小都是不可能的。
注释
使用此代码,一旦宽度达到 1200px,滚动条就会出现。如果您希望它发生
specifically only when >1200px
,只需更改 media query for 1201px
中的 1200px。
了解更多
mdn web doc中了解有关
overflow-x
属性的更多信息。mdn web doc中了解有关
white-space
属性的更多信息。w3Schools 文档和 mdn 网络文档 中了解有关
media queries
的更多信息。