PC端网页随屏幕大小自适应


vue2项目中使用 mixin配合sacle缩放实现自适应

  1. css样式文件
#app{
  width: 100%;
  height: 100%;
  position: relative;
  overflow-x: hidden;
  #index{
    position: absolute;
    width: 1920px; // 设计稿的宽度
    min-height: 100%;
    top: 0;
    left: 0;
    transform-origin: 0 0;
  }
}
  1. mixinDraw.js 文件
/* 屏幕适配 mixin 函数 */

// * 设计稿尺寸(px)
const baseWidth = 1920

export default {
  data() {
    return {
      // * 定时函数
      drawTiming: null
    }
  },
  mounted () {
    // 加载后先计算一遍缩放比例
    this.calcRate()
    // 生成一个监听器:窗口发生变化从新计算计算一遍缩放比例
    window.addEventListener('resize', this.resize)
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.resize)
  },
  methods: {
    calcRate () {
      // 拿到整个页面元素
      const appRef = this.$refs.zoom
      // 如果没有值就结束
      if (!appRef) return
      // 当前宽高比
      const currentRate = parseFloat((window.innerWidth / baseWidth).toFixed(5))
      if (appRef) {
          appRef.style.transform = `scale(${currentRate}, ${currentRate})`
      }
    },
    resize () {
      // 先清除计时器
      clearTimeout(this.drawTiming)
      // 开启计时器
      this.drawTiming = setTimeout(() => {
        this.calcRate()
      }, 200)
    }
  },
}
  1. vue文件中使用