<html><head>
<script src="js.js"></script>
<title></title>
<style>
#box
{
background:red;
width:100%;
height:100%;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
var x=$(window).width();
var y=$(window).height();
var a=x/2;
var b=y/2;
$(document).ready(function(){$("#box").css(width,a)});
$(document).ready(function(){$("#box").css(height,b});
</script>
</body>
</html>
我希望 div 宽度和高度在每个屏幕尺寸上都不同,但这段代码不起作用。任何帮助将不胜感激。 :)
最佳答案
你不需要 JS。使用该 CSS:
#box {
background-color: red;
width: 50%;
height: 50%;
/* left: 25%; */ /* uncomment if you want to center horizontally */
/* top: 25%; */ /* uncomment if you want to center vertically */
position: absolute;
}
工作样本:http://jsbin.com/eZUkADe/1/edit
如果您必须使用 jQuery 来实现,这里是:
$(document).ready(function(){
var x=$(window).width();
var y=$(window).height();
var a=x/2;
var b=y/2;
$("#box").css('width', a);
$("#box").css('height', b);
});
关于jquery - 根据屏幕宽高改变div的宽高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19926727/