将浏览器高度和宽度应用于div

时间:2018-02-04 10:11:57

标签: javascript jquery

我可以知道为什么我的div块没有显示?有人可以向我解释一下吗? https://jsfiddle.net/sw64j5qc/8/

function deviceSize() {
var myWidth = 0, myHeight = 0;
var block = document.getElementById("test");

if( typeof( window.innerWidth ) == 'number' ) {
  //Non-IE
  myWidth = window.innerWidth;
  myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
  //IE 6+ in 'standards compliant mode'
  myWidth = document.documentElement.clientWidth;
  myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
  //IE 4 compatible
  myWidth = document.body.clientWidth;
  myHeight = document.body.clientHeight;
}
block.style.width = myWidth;
block.style.height = myHeight;

window.alert( 'Width = ' + myWidth );
window.alert( 'Height = ' + myHeight );

} deviceSize();

2 个答案:

答案 0 :(得分:1)

您只是将数字传递给属性,而不是传递指定像素的字符串:

block.style.width = myWidth + "px";
block.style.height = myHeight + "px";

答案 1 :(得分:0)

您的div没有任何内容,如果您尝试

会发生什么
<div id="test" style="background-color: #000;">Some content here</div>