变量在控制台中更新.log但不在其他函数中更新

variable updating in console.log but not in another function

本文关键字:更新 其他 函数 log 变量 控制台      更新时间:2023-09-26

无法弄清楚我在这里做错了什么。

我使用 jquery 在屏幕调整大小时更新变量。该变量的目的是在 CSS 命中媒体查询 768px 时修复 scrollTop 函数的过冲。

这是我为调整大小函数准备的代码:

$(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未定义消息。这是为什么呢?

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();