写个适配的吧

90 阅读1分钟

前几天遇到个需求,用一张图片做背景,不管怎么缩放,或者各种屏幕都要铺满,,网上找了找,看到这种处理方式。

第一步:在data中设置默认宽高及缩放比

style: {
        width: '1920',
        height: '1080',
        transform: 'scaleY(1) scaleX(1) translate(-50%, -50%)'
        },

第二步:在methods里添加getScale和setScale

getScale() {
   const w = window.innerWidth / this.style.width;
   const h = window.innerHeight / this.style.height;
   return {x:w,y:h};
},
setScale() {
   let scale = this.getScale();
   this.style.transform = "scaleY(" + scale.y + ") scaleX(" + scale.x + ") translate(-50%, -50%)";
},

第三步:监听浏览器窗口改变事件

mounted() {
      let that = this;
      that.setScale();
      /*窗口改变事件*/
      $(window).resize(()=> {
        that.setScale();
      });
}

第四步:在css里设置最外层盒子样式

#screen{
    z-index: 100;
    transform-origin: 0 0;
    position: fixed;
    left: 50%;
    top: 50%;
    transition: 0.3s;第五步:在最外层盒子标签里设置行内样式
}

第五步:在最外层盒子标签里设置行内样式

<div id="screen" :style="{'width':`${style.width}px`,'height':`${style.height}px`,'transform':`${style.transform}`}">
</div>

第六步:放图片

<template>
    <div id="main" class="main">  
    </div>
</template>
<style rel="stylesheet/scss" lang="scss"  >
.main {
  height: 100%;
  width: 100%;
  background-image: url("../assets/images/bg.png");
}
</style>

完整代码:

<template>
  <div
    id="screen"
    :style="{
      width: `${style.width}px`,
      height: `${style.height}px`,
      transform: `${style.transform}`
    }"
  >
    <div id="main" class="main">
    </div>
 </div>
</template>
<script>
export default {
  name: 'ScaleBox',
  props: {},
  data () {
    return {
      style: {
        width: '1920',
        height: '1080',
        transform: 'scaleY(1) scaleX(1) translate(-50%, -50%)'
      }
    }
  },
  methods: {
    getScale () {
      const w = window.innerWidth / this.style.width
      const h = window.innerHeight / this.style.height
      return { x: w, y: h }
    },
    setScale () {
      const scale = this.getScale()
      this.style.transform =
        'scaleY(' + scale.y + ') scaleX(' + scale.x + ') translate(-50%, -50%)'
    }
  },
  mounted () {
    const that = this
    that.setScale()
    /* 窗口改变事件 */
    window.addEventListener('resize', function () {
      console.log('窗口发生变化')
      that.setScale()
    })
  }
}
</script>
 
<style lang="scss">
#screen {
  z-index: 100;
  transform-origin: 0 0;
  position: fixed;
  left: 50%;
  top: 50%;
  transition: 0.3s;
}
.box {
  width: 100%;
  height: 100%;
  background: url('@/assets/images/bac.png');
}
</style>     

转载自:blog.csdn.net/qq_38210427…

  版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
  原文链接:https://blog.csdn.net/qq_38210427/article/details/130345981