【发布时间】:2011-05-12 07:02:26
【问题描述】:
我不了解 javascript 中的变量。我试图在 localScroll 函数发生之前更改/计算“偏移量”(使用变量“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 容器居中到带有偏移量的窗口中,位于一个花哨的侧滚动网站中;)
【问题讨论】:
-
jslint.com 出现 3 个错误
-
即使没有错误,同样的问题仍然存在......
{top:0, left:theOffset}在执行时被评估,因此变量范围的闭包不会修复行为并使其动态而不知道/[ab]使用滚动到 API/internals 或重新调用 localScroll 函数。
标签: javascript jquery variables scope