gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:48:54 25 4
gpt4 key购买 nike

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

如何更改“$.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 容器置于窗口的中心,并在一个精美的侧滚动网站中进行偏移;)

最佳答案

您可以声明一个 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
});

关于JavaScript 变量不起作用。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4219478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com