Javascript变量不起作用。为什么? [英] Javascript variable not working. Why?

查看:111
本文介绍了Javascript变量不起作用。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm not understanding something about variables in javascript. I am trying to change/calculate "offset" (with the variable "theOffset") either before the localScroll function occurs, or more preferably when you resize the window. None of the instances below work, accept for the "//initialize offset".

如何让$ .localScroll中的变量theOffset改变?

How do I get the variable "theOffset" inside "$.localScroll" to change?

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容器居中到窗口,偏移量在一个奇特的一面滚动网站;)

If need to know, I am centering a div container to the window with the offset in a fancy side scrolling website ;)

推荐答案

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

You could declare a myOffset object that will be passed by reference to offset: You can also refine the almost quadruplicated function into a single named function:

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变量不起作用。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆