在vue3中使用scale对大屏幕做自适应处理

scale 的使用

  • 在做大屏或者是需要用到多个定位的情况下,屏幕的大小会改变布局,这种情况下可以使用 scale 对屏幕做自适应处理
<div class="login-container">
  <div class="login-main" ref="dataScreenRef"></div>
</div>
.login-container {
    
    
  width: 100%;
  height: 100%;
  transform-origin: 0 0;
  position: relative;
}
.login-main {
    
    
  width: 100%;
  height: 100%;
  position: absolute;
}
const dataScreenRef = ref(null);
const width = 1920;
const height = 1080;

/* 根据浏览器大小推断缩放比例 */
const getScale = (w = width, h = height) => {
    
    
  let ww = window.innerWidth / w;
  let wh = window.innerHeight / h;
  return ww < wh ? ww : wh;
};
/* 浏览器监听 resize 事件 */
const resize = () => {
    
    
  if (dataScreenRef.value) {
    
    
    dataScreenRef.value.style.transform = `scale(${
      
      getScale()}) translate(-50%, -50%)`;
  }
};

onMounted(() => {
    
    
  // 初始化时为外层盒子加上缩放属性,防止刷新界面时就已经缩放
  if (dataScreenRef.value) {
    
    
    dataScreenRef.value.style.transform = `scale(${
      
      getScale()}) translate(-50%, -50%)`;
    dataScreenRef.value.style.width = `${
      
      width}px`;
    dataScreenRef.value.style.height = `${
      
      height}px`;
  }
  window.addEventListener("resize", resize);
});

猜你喜欢

转载自blog.csdn.net/yuan0209/article/details/129559209
今日推荐