一、效果图:1920*1080全屏及非全屏
二、效果图:2880*1800全屏及非全屏
三、代码
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>scale 缩放</title><style>* {margin: 0;padding: 0;}html,body {height: 100%;}.data-view-wraper {height: 100%;overflow: hidden auto;position: relative;}#data-view {background: #071a37;border: 1px solid red;color: #fff;transform-origin: 0 0;transition: 0.1s;position: absolute;top: 50%;overflow-x: hidden;}</style></head><body><div class="data-view-wraper"><div id="data-view">网页内容</div></div></body><script>let _this = this;// 缩放比例let style = {width: "1920",height: "1080",transform: "scale(1)",top: "0%",};// 设置缩放比例let getScale = function () {const w = window.innerWidth / style.width;const h = window.innerHeight / style.height;return { x: w, y: h };};let setScale = function () {let scale = getScale();// 有留白的情况下上下居中,没有留白时居上0if (scale.x > scale.y) {style.top = 0;style.transform = "scale(" + scale.x + ")";} else {style.transform = "scale(" + scale.x + ") translate(0%, -50%)";style.top = "50%";}let datav = document.getElementById("data-view");datav.style = `width:${style.width}px;height:${style.height}px;transform:${style.transform};top:${style.top}`;};setScale();/*窗口改变事件*/window.onresize = function () {setScale();};</script>
</html>