我有几个像这样的点击语句
$('.button1').click(function() {
//grab current scroll position
var currentscrollpos = $(window).scrollTop()
$("html, body").animate({ scrollTop: 0 }, 500);
});
$('.button2').click(function() {
//go back to scroll position
$("html, body").animate({ scrollTop: currentscrollpos }, 500);
});
Run Code Online (Sandbox Code Playgroud)
我不知道如何获取当前滚动pos并将其存储在变量中,以便我可以在其他单击函数中使用它
有没有办法做到这一点?
在外部作用域中定义变量,以便它可用于其他函数:
var currentscrollpos;
$('.button1').click(function() {
currentscrollpos = $(window).scrollTop()
$("html, body").animate({ scrollTop: 0 }, 500);
});
$('.button2').click(function() {
$("html, body").animate({ scrollTop: currentscrollpos }, 500);
});
Run Code Online (Sandbox Code Playgroud)
您可以并且应该将其包装到闭包中以防止使用不必要的变量污染命名空间,但这应该至少让您开始.