繁体   English   中英

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

[英]Javascript variable not working. Why?

我对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
});

在jquery函数外部声明theOffset


var theOffset = 0;

jquery( function ( $ ) {
} )

我认为您的问题在这里:

offset: {top:0, left: theOffset,

首先,您缺少结尾的}。

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

您正在使用哪个版本的localScroll? 我下载了可以找到的最新源代码,即1.2.7,但我对偏移量一无所知。

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM