vue网页适配

最近做了个网站,关于网页适配不同电脑屏幕踩了几个坑,这里记录一下;

代码可以直接复制使用:

<template>
  <div ref="body" class="container">
    <div class="main"></div>
  </div>
</template>

<script>
import badySize from '@/mixins/bodySize'
export default {
  mixins:[badySize]
}
</script>

<style lang="less" scoped>
.container {
  height: 100%;
  .main {
    transform-origin: left top;
    position: relative;
    width: 1920px;
    height: 100%;
  }
}
</style>
export default {
  data() {
    return {
      mainStyle: "",//对main设置动态样式
    };
  },
  watch: {
    mainStyle: {
      handler() {
//把动态样式绑定到节点上
        this.$refs["body"]
        .querySelector(".main")
        .setAttribute("style", this.mainStyle);
      },
    },
  },
  async mounted() {
    await this.$nextTick();
    if (this.$refs["body"]) {
      let scale_x = this.$refs['body'].clientWidth / 1920;
      let h = (100 / scale_x).toFixed(2);
     //这里增加了一个height,防止因为宽高比例和1920:1080不一致导致底部出现空白
      this.mainStyle = `transform: scale(${scale_x});height:${h}%;`;
    }

    window.addEventListener("resize", () => {
      setTimeout(() => {
        if (this.$refs["body"]) {
          console.log("this.$refs['body'].clientWidth", this.$refs['body'].clientWidth)
          let scale_x = this.$refs['body'].clientWidth / 1920;
          let h = (100 / scale_x).toFixed(2);
          this.mainStyle = `transform: scale(${scale_x});height:${h}%;`;
        }
      })
    });
  },
};

这里使用了混入,在使用时在html中要在最外层div添加ref='body',第二层div添加class='main';我这边的标准尺寸是1920:1080;如果不是这个尺寸,请在对应的文件中修改为对应的尺寸

 我已经对不同的屏幕尺寸做了验证,基本上满足情况

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

travel_wsy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值