我有一个网络应用程序(Cordova),我已经设计了特定的宽度和高度。无论我戴上什么设备(手机,平板电脑,浏览器),我都希望文档正文缩小以适应。如果设备大于我的设计尺寸,则文档正文不应该向上扩展,而是将其自身置于窗口中。我认为我已经完成了比例计算,但我似乎无法让身体和内容在垂直和水平方向都居中。
这是一个演示(演示的小尺寸300x400):
调整“结果”窗口的大小以查看其重新缩放。我已经让它垂直工作(仅适用于Chrome),但水平缩小会使其向右移动。我完全采用与我在这里完全不同的方法。
相关代码:
<body>
<div id='div1'></div>
</body>
<script>
var max_width = 300;
var max_height = 400;
window.addEventListener('resize', on_window_resize);
on_window_resize();
function on_window_resize()
{
//if either window dimension is less than max, scale body to fit
var h_scale = window.innerHeight / max_height;
var w_scale = window.innerWidth / max_width;
var page_scale = 1;
if (h_scale < 1 || w_scale < 1)
{
page_scale = (h_scale < w_scale) ? h_scale : w_scale;
}
//display scale string
var div1 = document.getElementById('div1');
div1.innerHTML = "scale: " + page_scale.toFixed(2);
//scale body using webkit transforms
var scale_str = "scale(" + page_scale + ")";
document.body.style.webkitTransform = scale_str;
document.body.style.transform = scale_str;
//document.body.style.webkitTransformOrigin = "0 0";
//document.body.style.transformOrigin = "0 0";
//div1.style.webkitTransform = scale_str;
//div1.style.transform = scale_str;
//div1.style.webkitTransformOrigin = "0 0";
//div1.style.transformOrigin = "0 0";
}
</script>
<style>
body
{
overflow:hidden;
background-color: #444444;
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
#div1
{
overflow = 'hidden';
width: 300px;
height: 400px;
background-color: #dd4444;
font-size: 60px;
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
</style>
答案 0 :(得分:0)
更合适的方法是在CSS中使用媒体查询,根据窗口/视图的大小调整样式:
例如你的300x400盒子:
body
{
overflow:hidden;
background-color: #444444;
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
#div1
{
overflow = 'hidden';
width: 150px;
height: 200px;
background-color: #dd4444;
font-size: 60px;
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
@media all and (min-width: 300px) and (max-width:1000px) {
#div1 {
width: 300px;
height: 400px;
background-color: green;
}
}
小提琴:http://jsfiddle.net/44aAy/2/
当窗口最小宽度为300像素但不大于1000像素时,该框会改变大小并变为绿色。再次使盒子变小,它是红色的。
有一些框架,例如Twitter Bootstrap,Skeleton和其他内置的响应式网页设计。
答案 1 :(得分:0)
似乎设置的宽度强制它显示在右侧。