基於scale的自適應適配方案
阿新 • • 發佈:2022-12-05
在CSS3中,我們可以使用transform屬性的scale()方法來實現元素的縮放效果。縮放,指的是“縮小”和“放大”的意思。
- transform: scaleX(x); / 沿x軸方向縮放/
- transform: scaleY(y); / 沿y軸方向縮放/
- transform: scale(); / 同時沿x軸和y軸縮放/
適用場景
固定寬高比的Web應用,如大屏或者固定視窗業務應用
專案實戰
- 新建
resize.ts/js
檔案
import { ref } from "vue"; export default function windowResize() { // * 指向最外層容器 constscreenRef = ref(); // * 定時函式 const timer = ref(0); // * 預設縮放值 const scale = { width: "1", height: "1", }; // * 設計稿尺寸(px) const baseWidth = 1920; const baseHeight = 1080; // * 需保持的比例(預設1.77778) const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5)); const calcRate = () => {// 當前寬高比 const currentRate = parseFloat( (window.innerWidth / window.innerHeight).toFixed(5) ); if (screenRef.value) { if (currentRate > baseProportion) { // 表示更寬 scale.width = ( (window.innerHeight * baseProportion) / baseWidth ).toFixed(5); scale.height = (window.innerHeight / baseHeight).toFixed(5); screenRef.value.style.transform = `scale(${scale.width}, ${scale.height})`; } else { // 表示更高 scale.height = ( window.innerWidth / baseProportion / baseHeight ).toFixed(5); scale.width = (window.innerWidth / baseWidth).toFixed(5); screenRef.value.style.transform = `scale(${scale.width}, ${scale.height})`; } } }; const resize = () => { clearTimeout(timer.value); timer.value = window.setTimeout(() => { calcRate(); }, 200); }; // 改變視窗大小重新繪製 const windowDraw = () => { window.addEventListener("resize", resize); }; // 改變視窗大小重新繪製 const unWindowDraw = () => { window.removeEventListener("resize", resize); }; return { screenRef, calcRate, windowDraw, unWindowDraw, }; }
- 相關介面引入
resize.ts/js
<template> <div class="screen-container"> <div class="screen-content" ref="screenRef"> <span class="screen-title">基於scale的適配方案</span> <img class="screen-img" src="https://img2.baidu.com/it/u=1297807229,3828610143&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=281" alt=""> </div> </div> </template> <script setup lang="ts"> import windowResize from '../../utils/resize'; import {onMounted, onUnmounted} from 'vue'; const { screenRef, calcRate, windowDraw, unWindowDraw } = windowResize() onMounted(() => { // 監聽瀏覽器視窗尺寸變化 windowDraw() calcRate() }) onUnmounted(() => { unWindowDraw(); }) </script> <style lang="scss" scoped> .screen-container { height: 100%; background-color: lightcyan; display: flex; justify-content: center; align-items: center; .screen-content { width: 1920px; height: 1080px; background-color: #fff; display: flex; justify-content: center; align-items: center; flex-direction: column; .screen-title { font-size: 32px; } .screen-img { margin-top: 20px; } } } </style>