通過(guò)設(shè)置縮放比例,完成全屏適配
由于需要固定尺寸,所以需要內(nèi)部子控件用定位實(shí)現(xiàn)布局。
需要在body中設(shè)置定位
body {
position: relative;
width: 1920px;
height: 1080px;
transform-origin: left top;
}
固定比例適配
import { onMounted, onUnmounted } from "vue";
import _ from "lodash";
/**
大屏適配的 hooks
*/
export default function useScalePage(
targetWidth = 1920,
targetHeight = 1080,
targetProportion = 16 / 9
) {
const resizeFunc = _.throttle(function () {
triggerScale(); // 動(dòng)畫縮放網(wǎng)頁(yè)
}, 100);
onMounted(() => {
triggerScale(); // 動(dòng)畫縮放網(wǎng)頁(yè)
window.addEventListener("resize", resizeFunc);
});
onUnmounted(() => {
window.removeEventListener("resize", resizeFunc); // 釋放
});
// 大屏的適配
function triggerScale() {
// 1.設(shè)計(jì)稿的尺寸
let targetX = targetWidth;
let targetY = targetHeight;
let targetRatio = targetProportion; // 寬高比率
// 2.拿到當(dāng)前設(shè)備(瀏覽器)的寬度
let currentX =
document.documentElement.clientWidth || document.body.clientWidth;
let currentY =
document.documentElement.clientHeight || document.body.clientHeight;
// 3.計(jì)算縮放比例
let scaleRatio = currentX / targetX; // 參照寬度進(jìn)行縮放 ( 默認(rèn)情況 )
let currentRatio = currentX / currentY; // 寬高比率
// 超寬屏
if (currentRatio > targetRatio) {
// 4.開始縮放網(wǎng)頁(yè)
scaleRatio = currentY / targetY; // 參照高度進(jìn)行縮放
document.body.style = `width:${targetX}px; height:${targetY}px;transform: scale(${scaleRatio}) translateX(-50%); left: 50%`;
} else {
// 4.開始縮放網(wǎng)頁(yè)
document.body.style = `width:${targetX}px; height:${targetY}px; transform: scale(${scaleRatio})`;
}
}
}
等寬適配
import { onMounted, onUnmounted } from "vue";
import _ from "lodash";
/**
大屏適配的 hooks
*/
export default function useScalePageAllWidth() {
const resizeFunc = _.throttle(function () {
triggerScale(); // 動(dòng)畫縮放網(wǎng)頁(yè)
}, 100);
onMounted(() => {
triggerScale(); // 動(dòng)畫縮放網(wǎng)頁(yè)
window.addEventListener("resize", resizeFunc);
});
onUnmounted(() => {
window.removeEventListener("resize", resizeFunc); // 釋放
});
// 大屏的適配
// 用于執(zhí)行縮放和拉伸的函數(shù)
function triggerScale(targetWidth = 1920, targetHeight = 1080) {
const screenWidth = document.documentElement.clientWidth;
const scaleX = screenWidth / targetWidth;
// 設(shè)置 body 元素的樣式
document.body.style.width = targetWidth + "px";
document.body.style.height = targetHeight + "px";
document.body.style.transform = `scale(${scaleX})`;
document.body.style.transformOrigin = "top left";
}
}