Javascript变量不起作用。 为什么?

我不是在了解javascript中的变量。 我试图在localScroll函数发生之前更改/计算“offset”(使用变量“theOffset”),或者更优选地在调整窗口大小时。 下面的实例都不起作用,接受“// initialize offset”。

如何更改“$ .localScroll”中的变量“theOffset”?

jQuery(function( $ ){ //initialize offset var windowWidth = $(window).width(); if (windowWidth < 900) { theOffset = 0; } else { theOffset = ($(window).width() - 900) / -2; } $(window).resize(function() { //calculate offset var windowWidth = $(window).width(); if (windowWidth < 900) { theOffset = 0; } else { theOffset = ($(window).width() - 900) / -2; } }); $.localScroll({ target: '#content', queue:true, duration:1500, hash:true, stop:true, onBefore:function( e, anchor, $target ){ //calculate offset var windowWidth = $(window).width(); if (windowWidth < 900) { theOffset = 0; } else { theOffset = ($(window).width() - 900) / -2; } }, offset: {top:0, left: theOffset, onAfter:function( anchor, settings ){ if (windowWidth < 900) { theOffset = 0; } else { theOffset = ($(window).width() - 900) / -2; } } }); }); 

如果需要知道,我将一个div容器居中到窗口,并在一个花哨的侧滚动网站上有偏移量;)

您可以通过引用offset:来声明将传递的myOffset对象offset:您还可以将几乎四重的函数细化为单个命名函数:

 var myOffset = {top: 0, left: theOffset}; function calcOffset() { var windowWidth = $(window).width(); if (windowWidth < 900) { myOffset.left = 0; } else { myOffset.left = (windowWidth - 900) / -2; } } calcOffset(); // note leaving off the () will pass the function as a parameter instead of calling it $(window).resize(calcOffset); $.localScroll({ target: '#content', queue: true, duration: 1500, hash: true, stop: true, onBefore: calcOffset, offset: myOffset, onAfter: calcOffset }); 

在jquery函数之外声明theOffset

var theOffset = 0; jquery( function ( $ ) { } )
var theOffset = 0; jquery( function ( $ ) { } ) 

我认为你的问题在这里:

 offset: {top:0, left: theOffset, 

首先,你错过了一个尾随}。

其次,您正在执行所谓的“按值传递” – 调用$ .localscroll()时发送的值实际上是在OffOset中指定的值的副本。

您使用的是哪个版本的localScroll? 我下载了我能找到的最新资源,它是1.2.7,而我在任何地方都看不到偏移。

在没有看到localScroll源的情况下,没有直接的方法可以解决您的问题。 有时像这样的jQuery插件的作者提供了更新选项的方法。 如果不是这种情况,您可能必须修改localScroll源以通过函数回调而不是通过对象属性来获取偏移值:

 offset: {top:0, left: function() { return theOffset; } } 

请注意,如果不修改localScroll源以通过函数调用而不是options属性获取此数据,上述操作将无法工作。

请注意,在上面的示例中,如果再次调用setupSomeGlobals() ,则会创建一个新的闭包(stack-frame!)。 旧的gLogNumbergIncreaseNumbergSetNumber变量将被具有新闭包的新函数覆盖。 (在JavaScript中,每当你在另一个函数中声明一个函数时,每次调用外部函数时都会重新创建内部函数。)