gpt4 book ai didi

javascript - 简单的 jQuery 视差

转载 作者:行者123 更新时间:2023-11-28 10:28:40 27 4
gpt4 key购买 nike

我需要调试此 jQuery 的帮助,其中我操纵容器中元素的上边距,该容器具有固定大小并将溢出设置为隐藏,以便我可以创建视差效果。视差有效,但如果您向下滚动一个像素,然后重新加载页面,它就会中断。谁能帮我解决这个问题?这是代码。

//Parallax for Header
$(window).on("load", function() {
var startingScrollTop = parseInt($(window).scrollTop());
console.log(startingScrollTop);
var startingElementTop = parseInt($headerText.css("margin-top"));
console.log(startingElementTop);
$(window).on("scroll", function() {
var currentScrollTop = parseInt($(window).scrollTop());
console.log(currentScrollTop);
if(currentScrollTop > startingScrollTop) {
var scrollDistance = currentScrollTop - startingScrollTop;
console.log(scrollDistance);
var parallaxDistance = scrollDistance / 2;
console.log(parallaxDistance);
var newElementMarginTop = startingElementTop + parallaxDistance;
console.log(newElementMarginTop);
$headerText.css("margin-top", newElementMarginTop + "px");
} else if(currentScrollTop <= "0") {
$headerText.css("margin-top", "0px");
}
});
});

谢谢你的帮助。

最佳答案

我明白了,但我该如何简化呢?

//Parallax for Header
$(window).on("load", function() {
var startingScrollTop = 0;
console.log(startingScrollTop);
var startingElementTop = parseInt($headerText.css("margin-top"));
console.log(startingElementTop);
//Re-use this on scroll
var currentScrollTop = parseInt($(window).scrollTop());
console.log(currentScrollTop);
if(currentScrollTop > startingScrollTop) {
var scrollDistance = currentScrollTop - startingScrollTop;
console.log(scrollDistance);
var parallaxDistance = scrollDistance / 2;
console.log(parallaxDistance);
var newElementMarginTop = startingElementTop + parallaxDistance;
console.log(newElementMarginTop);
$headerText.css("margin-top", newElementMarginTop + "px");
} else if(currentScrollTop <= "0") {
$headerText.css("margin-top", "0px");
}
//Put the re-used code here
$(window).on("scroll", function() {
var currentScrollTop = parseInt($(window).scrollTop());
console.log(currentScrollTop);
if(currentScrollTop > startingScrollTop) {
var scrollDistance = currentScrollTop - startingScrollTop;
console.log(scrollDistance);
var parallaxDistance = scrollDistance / 2;
console.log(parallaxDistance);
var newElementMarginTop = startingElementTop + parallaxDistance;
console.log(newElementMarginTop);
$headerText.css("margin-top", newElementMarginTop + "px");
} else if(currentScrollTop <= "0") {
$headerText.css("margin-top", "0px");
}
});
});

我能否将重复使用的代码转换为可以在加载、滚动或任何其他处理程序上运行的函数?

关于javascript - 简单的 jQuery 视差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23614824/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com