我正在研究这个小代码:
$(window).scroll(function(){
var scrollTop = $(window).scrollTop(),
windowHeight = $(window).height(),
elem = $('#coverage-area-load-trigger').offset().top,
final = elem - windowHeight,
distance = final - scrollTop;
if(distance < 0){
console.log('Load Now');
}
});
我应该如何写这个&#34;立即加载&#34;只记录一次?
我要更换&#34;立即加载&#34;控制台日志:
$('#coverage-area').attr('src', 'https://www.google.com/maps/...');
触发&#34;覆盖范围&#34;当iframe进入视图时加载。
感谢您的帮助!
答案 0 :(得分:2)
只需添加一个变量来检查事件是否被触发:
var coverageAreaTriggered = false;
$(window).scroll(function () {
if (!coverageAreaTriggered ){
var scrollTop = $(window).scrollTop(),
windowHeight = $(window).height(),
elem = $('#coverage-area-load-trigger').offset().top,
final = elem - windowHeight,
distance = final - scrollTop;
if (distance < 0) {
console.log('Load Now');
coverageAreaTriggered = true;
}
}
});
答案 1 :(得分:1)
另一种选择是使用
$(window).on("scroll", function(){
...
if(distance < 0){
console.log("load now");
$(window).off("scroll");
}
});
关闭时,调用时会删除事件处理程序。因此,在它被触发后,它会自行移除。