根据浏览器窗口等比缩放页面
实现思路
- 通过css的transform scale属性对页面body元素进行缩放
- 缩放比例为实际窗口尺寸/设置的body像素尺寸,选择(窗口宽/body宽)和(窗口高/body高)中较小的一个
- body缩放之后,位置相对于窗口出现偏移,许需要调整body的margin
代码实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>等比缩放</title>
<style type="text/css">
html {
background: #757575
}
body {
margin: 0;
background: #a8a8a8;
}
</style>
</head>
<body id="body">
<div id="container">
<div style="font-size: 40px">40px文字</div>
<div style="font-size: 20px">20px文字</div>
<div style="font-size: 20px">拖动浏览器窗口大小,查看缩放效果</div>
<button>按钮</button>
</div>
<script type="text/javascript">
let cw = 1920,ch = 1080
let body = document.getElementById('body')
body.style.width = `${cw}px`
body.style.height = `${ch}px`
function windowResize() {
let w = window.innerWidth, h = window.innerHeight
let r = w / cw < h / ch ? w / cw : h / ch
body.style.transform = `scale( ${r})`
body.style.marginLeft = (-(cw - r * cw) / 2 + (w - r * cw) / 2) + 'px'
body.style.marginTop = (-(ch - r * ch) / 2 + (h - r * ch) / 2) + 'px'
body.style.marginBottom = (-(h>ch?h:ch - r * ch)) + 'px'
body.style.marginRight = (-(w>cw?w:cw - r * cw)) + 'px'
}
windowResize()
window.addEventListener('resize', windowResize);
</script>
</body>
</html>