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

文章介绍了如何在Vue项目中利用rem单位和窗口大小监听来实现字体自适应。通过定义screenWidth变量,监听窗口resize事件,并用定时器避免频繁触发,调整html标签的字体大小以适应不同屏幕宽度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值