所以我有点新的javascript和jquery仍然所以我坚持这个小问题。 这里的问题是“currentId”变量。 这个变量在滚动事件期间获取一个值,但我需要它在滚动事件通过后仍然保留,并在下一个滚动事件中考虑到它只是返回null或未定义。
任何人都可以指出我在正确的方向吗?因为我现在读了一天哈哈哈。
$("#content").on("scroll resize", function(){ //on scroll
var pos=$("#frontpage").offset(); //take front page position in variable
$('.page').each(function(){ //for each div with a class of page
if(pos.top >= $(this).offset().top && pos.top < $(this).next().offset().top){ //if this divs position is in the correct range
if (currentId != $(this).attr('id')|| typeof currentId == 'undefined') { //if currentId Var is diffrent from this divs id or is undefined
var currentId = $(this).attr('id'); //set currentId Var to this divs id
$(this).addClass( "foo" ); //add class foo to this div
}else{
//Else do nothing
}; //endIfElse
}else{
$(this).removeClass( "foo" ); //Else remove the foo class from this div
}; //endIfElse
}); //end each
});
答案 0 :(得分:1)
为什么不简单地将var currentId
简单地放在任何函数或处理程序之外?只要显示页面,它就不会消失。
现在要使其真正持久,您可以存储和读取Cookie(使用document.cookie
)。
答案 1 :(得分:1)
这段代码一般不太好,但为了解决您的具体问题,请将变量的声明放在代码块之外:
var currentId;
$("#content").on("scroll resize", function() { //on scroll
var pos = $("#frontpage").offset(); //take front page position in variable
$('.page').each(function($currentId) { //for each div with a class of page
if (pos.top >= $(this).offset().top && pos.top < $(this).next().offset().top) { //if this divs position is in the correct range
if (currentId != $(this).attr('id') || typeof currentId == 'undefined') { //if currentId Var is diffrent from this divs id or is undefined
currentId = $(this).attr('id'); //set currentId Var to this divs id
$(this).addClass("foo"); //add class foo to this div
} else {
//Else do nothing
}; //endIfElse
} else {
$(this).removeClass("foo"); //Else remove the foo class from this div
}; //endIfElse
}); //end each
});