gpt4 book ai didi

javascript - 缩放和居中网页以适应任何设备/窗口尺寸

转载 作者:行者123 更新时间:2023-11-28 10:26:54 26 4
gpt4 key购买 nike

我有一个网络应用程序 (Cordova),我设计了一个特定的宽度和高度。我希望文档正文按比例缩小以适应我放置的任何设备(手机、平板电脑、浏览器)。如果设备大于我设计的尺寸,文档正文不应放大,而是在窗口中居中。我认为我已经进行了比例计算,但我似乎无法让正文和内容在垂直和水平方向上居中。

这是一个演示(用于演示的小尺寸 300x400):

http://jsfiddle.net/D2e4W/

调整结果窗口的大小以查看它的重新缩放。我让它垂直工作(仅限 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>

最佳答案

更合适的方法是在 CSS 中使用媒体查询,根据窗口/ View 的大小调整样式:

例如您的 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;
}
}

fiddle :http://jsfiddle.net/44aAy/2/

当窗口宽度至少为 300 像素但不大于 1000 像素时,框将改变大小并变为绿色。再次缩小盒子,它是红色的。

有一些框架,例如 Twitter Bootstrap、Skeleton 和其他内置用于响应式网页设计的框架。

关于javascript - 缩放和居中网页以适应任何设备/窗口尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23703371/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com