<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.container {
width: 100vw;
height: 100vh;
background: url(../public/bg.png) no-repeat;
background-size: cover;
}
.box {
width: 1920px;
height: 1080px;
background-color: red;
transform-origin: top left;
position: fixed;
left: 50%;
top: 50%;
}
.top {
width: 100px;
height: 100px;
background-color: hotpink;
}
.bottom {
width: 100px;
height: 100px;
background-color: skyblue;
margin-left: 50px;
margin-top: 50px;
}
</style>
</head>
<body>
<div class="container">
<!--数据展示区域-->
<div class="box">
<div class="top">我是祖国的</div>
<div class="bottom">傻逼啊啊啊</div>
</div>
</div>
</body>
</html>
<script>
//控制数据大屏的放大与缩小,里面的内容文字也会跟着缩放
let box = document.querySelector('.box');
//translate(-50%,-50%)必须写在这里,第一,transform的值只能写一起,不能分开写。第二:必须先缩小,在移动,不然缩小的中心点会随着translate变动。
box.style.transform = `scale(${getScale()}) translate(-50%,-50%)`
console.log(box.style.transform);
//计算缩放比例
function getScale(w = 1920, h = 1080) {
const ww = window.innerWidth / w;//算出scale需要的比例 * w = 当前宽度
const wh = window.innerHeight / h;
//设备的宽度和高度,哪个被缩小的比另一个小了,就把另一个也缩小,保持最小的跟另一个不小的比例是一样的。
//放大因为不可能两边都一起放大,会超出屏幕不行,但是如果放大后是一样比例的,那么这个能够保持
放大后比例也是不变的。
//缩小最大是1920,缩小的比例参数效果是保持有一个适应边宽或边长的。
return ww < wh ? ww : wh;
}
//window的窗口变动事件
window.onresize = ()=>{
box.style.transform = `scale(${getScale()}) translate(-50%,-50%)`
}
</script>
解决屏幕缩放后保持布局原本设计的比例不变
于 2023-10-19 10:54:19 首次发布