我不知道我在这里做错了什么。
我使用jquery更新屏幕大小上的变量。该变量的目的是修复scrollTop函数在CSS访问媒体查询768px时的超调。
下面是用于调整大小函数的代码:
$(window).resize(function(){
if (window.matchMedia('(max-width: 768px)').matches) {
var scrollovershoot = 40;console.log(scrollovershoot);
} else {
var scrollovershoot = 0;console.log(scrollovershoot);
}
});现在,上面的函数的工作原理和它应该做的一样,即当屏幕大小达到或低于768 (即40的值)时,它会记录正确的scrollovershoot变量。不过,在我的其他scrollTop函数中,变量似乎没有更新(它没有更新scrollTop偏移量)。以下是滚动函数的代码:
$(".fixed-navigation-follow li a, .see-next a, .more-info-cta, .flipper-container a, #main-atf-cta").click(function (){
var scrollmeto = $(this).attr("href");
$('html, body').animate({
scrollTop: $(scrollmeto).offset().top - scrollovershoot
}, 1000);
return false;
});当我调整屏幕大小时,我从我的第一个函数获得自动控制台日志记录,显示正确的值,但是,当我停止调整大小,只在控制台中键入console.log(scrollovershoot);时,就会得到未定义的scrollovershoot消息。为什么会这样呢?
发布于 2016-01-14 15:26:01
scrollovershoot需要是一个全局变量。您是在函数级别定义它。
当您更改关键字var时,删除它,以防止它在您的函数范围内被定义,并在您的代码段之上定义它,使其成为全局的。
或者,为了更安全,您可以通过将它分配给window (这是一个全局对象)来使其具有全局性。
window.scrollovershoot = 0;
$(window).resize(function(){
if (window.matchMedia('(max-width: 768px)').matches) {
window.scrollovershoot = 40;console.log(window.scrollovershoot);
} else {
window.scrollovershoot = 0;console.log(window.scrollovershoot);
}
});在你的jQuery中:
$(".fixed-navigation-follow li a, .see-next a, .more-info-cta, .flipper-container a, #main-atf-cta").click(function (){
var scrollmeto = $(this).attr("href");
$('html, body').animate({
scrollTop: $(scrollmeto).offset().top - window.scrollovershoot
}, 1000);
return false;
});当您使用var时,您在函数的作用域中定义了一个变量。在函数之前定义它,使得它是全局的,可以被其他函数访问。
// In the browser, `window` is a global object referring to the browser object module.
// More info: http://www.w3schools.com/js/js_window.asp.
var myGlobalVar;
function f() {
myGlobalVar = 'something';
window.myVar = 'something else';
var myLocalVar = 'some other things';
}
function g() {
console.log(myGlobalVar); // this works
console.log(window.myVar); // this also works
console.log(myLocalVar); // this does NOT work
}
f();
g();https://stackoverflow.com/questions/34793211
复制相似问题