用于Div高度的Javascript,使其更快

时间:2011-05-20 15:07:13

标签: javascript html controls height

我有以下脚本来控制任何带有ID的元素,在这种情况下,它是一个带有“包装”ID的div:

 window.onload = window.onresize = function ResizeIFrame() {
                var div = document.getElementById("wrapper");
                var myWidth = 0, myHeight = 0;

                if (typeof (window.innerWidth) == 'number') {
                    //Non-IE
                    myWidth = window.innerWidth ;
                    myHeight = window.innerHeight - 90;

                } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                    //IE 6+ in 'standards compliant mode'
                    myWidth = document.documentElement.clientWidth ;
                    myHeight = document.documentElement.clientHeight - 90 ;
                } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                    //IE 4 compatible
                    myWidth = document.body.clientWidth;
                    myHeight = document.body.clientHeight - 90;
                }
                div.style.width = myWidth + 'px';
                div.style.height = myHeight + 'px';
            }  



在此网络中,您可以看到它是如何工作的:http://www.jmquintela.cl/?page_id=145 问题是脚本等待页面完全加载以运行该功能并调整窗口大小,或等待用户手动调整窗口大小。 但是加载页面可能需要一段时间,我希望脚本在窗口完全加载之前自行执行,这样用户就可以在中间导航。 我尝试像这样调用函数,但不起作用:


    ResizeIFrame()
    
请帮忙! 再见!

2 个答案:

答案 0 :(得分:1)

window.onload在所有图像和iframe完成加载之前不会触发,这就是为什么所有主要的JS库都会尝试识别DOM何时可以操作,这通常会更快地发生。如果您不使用/不想使用其中一个库,那么这里有一个非常轻量级的跨浏览器DOM-ready帮助程序:https://github.com/ded/domready#readme

答案 1 :(得分:0)

试试这个:

 function ResizeIFrame() {
            var div = document.getElementById("wrapper");
            var myWidth = 0, myHeight = 0;

            if (typeof (window.innerWidth) == 'number') {
                //Non-IE
                myWidth = window.innerWidth ;
                myHeight = window.innerHeight - 90;

            } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                //IE 6+ in 'standards compliant mode'
                myWidth = document.documentElement.clientWidth ;
                myHeight = document.documentElement.clientHeight - 90 ;
            } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                //IE 4 compatible
                myWidth = document.body.clientWidth;
                myHeight = document.body.clientHeight - 90;
            }
            div.style.width = myWidth + 'px';
            div.style.height = myHeight + 'px';
        }  

window.onload = window.onresize =  ResizeIFrame;

//Then you can just do:
ResizeIFrame(); //whenever you desire