5

我已经查看了很多关于这个主题的问题,但似乎无法找出我的代码有什么问题。任何帮助将不胜感激!

$(window).resize(function(){
   var newwidth = $(window).innerWidth();
   var newheight = $(window).innerHeight();      
   $("#element").height(newheight).width(newwidth);
       });

如果调整窗口大小,我正在尝试将#element 调整为与窗口相同的高度和宽度。

4

5 回答 5

13

关于.innerWidth(),来自文档

此方法不适用于窗口和文档对象;对于这些,请改用 .width() 。

也有相同的注释.innerHeight()

所以你需要使用.width()and .height()

$(window).resize(function(){
    var newwidth = $(window).width();
    var newheight = $(window).height();      
    $("#element").height(newheight).width(newwidth);
});
于 2012-07-06T17:41:07.963 回答
1

试试这个:

$(window).resize(function(){
   var newwidth = $(window).width();
   var newheight = $(window).height();      
   $("#element").css({"height": newheight, "width": newwidth });
});
于 2012-07-06T17:41:30.197 回答
1

在纯 Javascript 中,您可以这样做:

    var viewportwidth;
    var viewportheight;

    // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight

    if (typeof window.innerWidth != 'undefined')
    {
        viewportwidth = window.innerWidth,
        viewportheight = window.innerHeight
    }

    // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

    else if (typeof document.documentElement != 'undefined'
     && typeof document.documentElement.clientWidth !=
     'undefined' && document.documentElement.clientWidth != 0)
    {
         viewportwidth = document.documentElement.clientWidth,
         viewportheight = document.documentElement.clientHeight
    }

    // older versions of IE

    else
    {
         viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
         viewportheight = document.getElementsByTagName('body')[0].clientHeight
    }
    var mydiv = document.getElementById("element");
    mydiv.style.height=viewportheight'px';
    mydiv.style.width=viewportwidth+'px';
于 2012-07-06T17:44:30.383 回答
1

jsFiddle

 $(window).resize(function(){
var newwidth = $(window).width();
var newheight = $(window).height();      
$("#element").height(newheight).width(newwidth);
  });​

两者都适合我

更新

 $(window).resize(function(){
var newwidth = $(window).innerWidth();
var newheight = $(window).innerHeight();      
$("#element").height(newheight).width(newwidth);
  });​
于 2012-07-06T17:47:42.580 回答
0

你总是可以只使用 CSS:

#element {width:100%; height:100%; position:fixed; }
于 2012-07-06T17:43:40.407 回答