下面有读取窗口高度的代码,当滚动不到50%时执行一个操作,当滚动超过50%时执行另一个操作--这很好--但是,它在滚动后反复执行操作,因此在滚动结束时重复操作数千次--我如何将其修改为只调用一次,然后直到滚动高度更改到另一个阈值为止?
这里的代码示例显示了问题-查看console.log以查看重新发生的操作。
( function($) {
function homeMCformSwitching() {
var t=$(window).scrollTop()+1;
var c=$('html').outerHeight();
var p=(t/c*100).toFixed(0);
if (p<50) {
console.log("do action for top half");
}
if (p>50) {
console.log("do action for bottom half");
}
}
homeMCformSwitching();
$(window).scroll(function() { homeMCformSwitching(); });
})(jQuery);
div { height: 3000px; background: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
Check console to see the log firing many times over and over on scroll
</div>
发布于 2022-02-25 10:56:27
您必须存储在达到滚动阈值时执行的最后一个操作。因此,在具有相同阈值的后续滚动中,您可以跳过相同的操作。
示例:
( function($) {
var previousWidth = jQuery(window).width();
/** changed here **/
let lastAction = 0;
function homeMCformSwitching() {
var t=$(window).scrollTop()+1;
var c=$('html').outerHeight();
var p=(t/c*100).toFixed(0);
/** changed here **/
if (p<50 && lastAction != -1) {
lastAction = -1;
console.log("do action for top half");
}
/** changed here **/
if (p>50 && lastAction != 1) {
lastAction = 1;
console.log("do action for bottom half");
}
}
homeMCformSwitching();
$(window).scroll(function() { homeMCformSwitching(); });
})(jQuery);
https://stackoverflow.com/questions/71264683
复制相似问题