Javascript:代码在投入使用时不会被执行

时间:2016-03-01 22:32:28

标签: javascript

我有这个有用的Javascript代码,可以对initresize进行一些调整:

(function (w) {

  w.init = function () {

    var w = window.innerWidth;
    var h = window.innerHeight; 

    //resize_font;
    var fs = parseInt(w / 26);   
    document.body.style.fontSize = fs + "px";

    //resize_cover;
    var logo = get_by_id("logo");
    var logo_height = logo.clientHeight;  
    var menu = get_by_id("menu");
    var menu_height = menu.clientHeight; 
    var cover_height = logo_height + menu_height;
    var distance_top = (h - cover_height) / 2.5;

    var container = get_by_id("container");
    container.style.paddingTop = distance_top + "px"; 
  }

  w.resize = function () {

    var w = window.innerWidth;
    var h = window.innerHeight; 

    //resize_font;
    var fs = parseInt(w / 26);   
    document.body.style.fontSize = fs + "px";

    //resize_cover;
    var logo = get_by_id("logo");
    var logo_height = logo.clientHeight;  
    var menu = get_by_id("menu");
    var menu_height = menu.clientHeight; 
    var cover_height = logo_height + menu_height;
    var distance_top = (h - cover_height) / 2.5;

    var container = get_by_id("container");
    container.style.paddingTop = distance_top + "px"; 
  }
}

现在我想重构代码以调整字体大小并覆盖到函数中,但是 我无法让它发挥作用。我试过这个:

(function (w) {

  w.init = function () {
    var w = window.innerWidth;
    var h = window.innerHeight; 

    resize_font;
    resize_cover;
  }

  w.resize = function () {
    var w = window.innerWidth;
    var h = window.innerHeight; 

    resize_font;
    resize_cover;
  }

  function resize_cover() {
    var logo = get_by_id("logo");
    var logo_height = logo.clientHeight;  
    var menu = get_by_id("menu");
    var menu_height = menu.clientHeight; 
    var cover_height = logo_height + menu_height;
    var distance_top = (h - cover_height) / 2.5;

    var container = get_by_id("container");
    container.style.paddingTop = distance_top + "px";        
  }

  function resize_font() {
    var fs = parseInt(w / 26);   
    document.body.style.fontSize = fs + "px";        
  }
}

控制台没有显示任何错误,但调整大小并没有发生。我做错了什么?

3 个答案:

答案 0 :(得分:3)

您需要在init中调用函数并调整事件函数的大小。 你有:

resize_font;
resize_cover;

你需要:

resize_font();
resize_cover();

函数的名称只是对它的引用,这就是为什么你没有看到任何错误。你现在拥有的是类似的说法:

var x = 1;
x;

答案 1 :(得分:2)

看起来你的问题是:

resize_font;
resize_cover;

我认为你的意思是

resize_font();
resize_cover();

答案 2 :(得分:1)

似乎你忘了执行这些函数,只是提到了指针。

请尝试更改:

resize_font;
resize_cover;

resize_font();
resize_cover();