四个正方形div横向排布,宽度根据页面的大小进行变化

57 阅读1分钟

四个正方形div横向排布,宽度根据页面的大小进行变化。 例如,页面的宽度为1000px,那么div的宽度为1000/5=200,div的宽高为200,然后横向均匀排布

<template>
  <div class="container">
    <div 
      v-for="item in 4" 
      :key="item"
      :class="{square: true, active: item === selected}"
      @click="selected = item"
      :style="{ width: `${size}px`, height: `${size}px` }">
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        size: 0,
        selected: 0
      }
    },

    mounted() {
      this.setSize()
      window.addEventListener('resize', this.setSize)
    },

    beforeDestroy() {
      window.removeEventListener('resize', this.setSize)
    },

    methods: {
      setSize() {
        const containerWidth = document.querySelector('.container').clientWidth //获取容器宽度
        const numSquares = 4 //正方形个数
        this.size = Math.floor(containerWidth / (numSquares + 1)) //计算正方形大小(加一是为了考虑间距)
      }
    }
  }
</script>

<style scoped>
  .container {
    width: 100%;
    display: flex;
    justify-content: space-evenly;
  }

  .square {
    background-color: #aaaaaa;
  }

  .active {
    background-color: lightblue !important;
  }
</style>