gpt4 book ai didi

jQuery 视差效果和滞后

转载 作者:行者123 更新时间:2023-12-01 07:04:05 25 4
gpt4 key购买 nike

我有一个带有标题和内容的页面。向下滚动时,标题菜单粘在顶部,而内容具有一种“视差”效果(它向上移动的速度比标题快,这正是我所需要的)。

我的小 jQuery 脚本对于“视差”效果效果很好,但是当向下滚动达到最大时,内容开始卡顿/滞后。该脚本似乎不断尝试将内容连续向上移动(至少使用 Apple Magic Mouse),这会产生这种不雅的副作用。

如何防止这种情况发生?

PS:为了清楚地显示卡顿问题,我夸大了 JSFiddle 中的视差效果。

PPS:测试时请确保您有一个可滚动的页面(浏览器高度较小),否则当然不会出现效果和问题。

//sticky header menu

$(window).scroll(function() {
if ($(document).scrollTop() > 92) {
if (!$('.fixed').length) {
$('.menu').addClass('fixed');
}
} else {
if ($('.fixed').length) {
$('.menu').removeClass('fixed');
}
}
});

// Parallax of content on scroll

var iCurScrollPos = 0;
$(window).scroll(function() {
iCurScrollPos = $(this).scrollTop();
$('.content').css('margin-top', -iCurScrollPos * 1.2 + 'px')
});
body {
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
background: #ccc;
}

header {
position: relative;
width: 100%;
background: #fff;
z-index: 1;
height: 146px;
}

.void {
position: relative;
width: 100%;
height: 100px;
}

.menu {
position: relative;
width: 100%;
height: 54px;
background: #aaa;
}

.fixed {
position: fixed;
left: 0px;
top: 0px;
}

img {
width: 100%
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

<header>
<div class="void"></div>
<nav class="menu"></nav>
</header>

<div class="content">
<img src="https://farm8.staticflickr.com/7632/16990947835_3894284fd8_b.jpg">
</div>

JSFiddle

https://jsfiddle.net/v6g43mkL/1/

最佳答案

您可以使用滚动位置的历史记录来通过比较最后 2 个位置是否与第 3 个和第 4 个位置相同来确定是否发生卡顿效应:

$(window).scroll(function() {
if ($(document).scrollTop() > 92){
if (!$('.fixed').length){$('.menu').addClass('fixed');}
}
else {
if ($('.fixed').length){$('.menu').removeClass('fixed');}
}
});

// Parallax of page on scroll

var iCurScrollPos = 0;
// Contains the last 4 scroll positons.
var lastPositions = [];

$(window).scroll(function () {
iCurScrollPos = $(this).scrollTop();

lastPositions.push(iCurScrollPos);
// Control over when locaties are marked as duplicates. Use it to fine tune the response.
var duplicateRange = 20;

// The stutter bug can be caught be checking if two last locations are the same as the 3rd and 4th.
if(Math.abs(lastPositions[0] - lastPositions[2]) < duplicateRange && Math.abs(lastPositions[1] - lastPositions[3]) < duplicateRange){
lastPositions = [];
return;
}

console.log(lastPositions);
if(lastPositions.length === 4){
lastPositions = [];
}



$('.content').css('margin-top',-iCurScrollPos*1.2+'px')
});

jsFiddle:https://jsfiddle.net/maartendev/sj5egqhd/25/

关于jQuery 视差效果和滞后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57710814/

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