vue项目实现大屏PC端字体自适应

我们字体自适应选择使用rem作为单位,通过监听窗口大小的变化,更新1rem的对应的px数来实现字体自适应。

注意该方法,我们需要在APP.vue文件中实现,

  1. 首先APP.vue文件中,定义屏幕宽度的变量screenWidth
data() {
    return {
      screenWidth:
        window.innerWidth ||
        document.documentElement.clientWidth ||
        document.body.clientWidth,
    };
  },

2.监听窗口变化,将值赋给screenWidth看,注意监听方法写在mounted(){}钩子中,防止无法获取窗口值。

mounted() {
    const that = this;
    window.onresize = () => {
      return (() => {
        (window.screenWidth =
          window.innerWidth ||
          document.documentElement.clientWidth ||
          document.body.clientWidth),
          (that.screenWidth = window.screenWidth);
        this.fun();
      })();
    };
  },

3.为了避免频繁触发resize函数导致页面卡顿,使用定时器和watch:{}监听screenWidth值的改变,一旦监听到的screenWidth值改变,就将其重新赋给data里的screenWidth

 watch: {
    screenWidth(val) {
      // 为了避免频繁触发resize函数导致页面卡顿,使用定时器
      if (!this.timer) {
        // 一旦监听到的screenWidth值改变,就将其重新赋给data里的screenWidth
        this.screenWidth = val;
        this.timer = true;
        let that = this;
        setTimeout(function () {
          that.timer = false;
        }, 400);
      }
    },
  },

4.最后定义fun函数,设置html标签的字体大小自适应 为了使得rem单位自适应

 methods: {
    fun() {
      const that = this;
      var htmlobj = document.getElementsByTagName("html")[0];
      htmlobj.style.fontSize = (that.screenWidth / 1920) * 20 + "px";
    }
 }

完整代码如下:

<script >
export default {
  name: "App",
  data() {
    return {
      screenWidth:
        window.innerWidth ||
        document.documentElement.clientWidth ||
        document.body.clientWidth,
    };
  },
  created() {
    this.lastTime = new Date().getTime();
    this.fun();
  },
  mounted() {
    const that = this;
    window.onresize = () => {
      return (() => {
        (window.screenWidth =
          window.innerWidth ||
          document.documentElement.clientWidth ||
          document.body.clientWidth),
          (that.screenWidth = window.screenWidth);
        this.fun();
      })();
    };
  },
  watch: {
    screenWidth(val) {
      // 为了避免频繁触发resize函数导致页面卡顿,使用定时器
      if (!this.timer) {
        // 一旦监听到的screenWidth值改变,就将其重新赋给data里的screenWidth
        this.screenWidth = val;
        this.timer = true;
        let that = this;
        setTimeout(function () {
          that.timer = false;
        }, 400);
      }
    },
  },
  methods: {
    // 设置html标签的字体大小自适应   为了使得rem单位自适应
    fun() {
      const that = this;
      var htmlobj = document.getElementsByTagName("html")[0];
      htmlobj.style.fontSize = (that.screenWidth / 1920) * 20 + "px";
    }
  },
};
</script>

Logo

智屏生态联盟致力于大屏生态发展,利用大屏快应用技术降低开发者开发、发布大屏应用门槛

更多推荐