js 小白问个小问题希望各位大牛指点下迷津

2016-11-08 21:15:57 +08:00
 djkloop

index.js
define(function() {

function Window() {

}

Window.prototype = {

    //window 事件
    windowscreen: function(id) {
        //window.onload = this.getHeight(options);
        var that = this;
        window.onresize = function(id) {
                that.getHeight(id);
               //执行 onresize 函数的时候浏览器报错
               // index.js:32 Uncaught TypeError: Cannot read property 'style' of null
        }
        setInterval(this.getHeight(id), 1000);
    },
    //获取屏幕高度让指定元素垂直居中
    getHeight: function(id) {
        var oDiv = document.getElementById(id),
            screenHeight = document.documentElement.clientHeight;
            oDiv.style.marginTop = (parseInt(screenHeight / 2)) + 'px';
    }
}
return {
    Window: Window
};

});

这是另外一个 js 文件 main.js-- require.config({ paths:{ "jquery": "jquery.min" } })

require(['jquery','index'],function($,i) { var getHeight = new i.Window(); // getHeight.getHeight('header'); // getHeight.getHeight('main'); // getHeight.getHeight('bottom'); getHeight.getHeight('header'); getHeight.windowscreen('header'); })

第一次接触这种写法想学习学习...处处都是坑....- -。希望大牛能够指点下我这个小白....该怎么样修改才行啊...

2162 次点击
所在节点    JavaScript
6 条回复
djkloop
2016-11-08 21:18:42 +08:00
第一次刚加载的时候可以执行..但是只要改变窗口就会报错....这是什么原因呢?我传了 id 进去 margintop 应该有值啊....
djkloop
2016-11-08 23:49:07 +08:00
好吧解决了...原因是 setIntreval 也是 window 的下的方法...粗心害死人...
setInterval(function () {
that.getHeight(id);
},
这样就可以了
itkdqwzero
2016-11-09 07:42:44 +08:00
不懂 ,用什么框架吗?
nodejs ?
兼容性测试通过吗?
为什么不用 jQuery ?
yuuko
2016-11-09 08:49:11 +08:00
请看 js 事件,把 id 放第二个参数,第一个参数是事件对象
djkloop
2016-11-09 12:02:24 +08:00
@itkdqwzero 就是新手想学习学习这种写法,前面没写过这种。😳
djkloop
2016-11-09 12:03:28 +08:00
@yuuko 嗯嗯,好的,谢谢您。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/319095

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX