Vue 动态设置元素高度

1. Vue文件如下

<template>
  <div :style="autoHeight"></div>
</template>
<script>
  let windowHeight = parseInt(window.innerHeight)
  export default {
    data() {
      return {
        windowHeight: windowHeight,
        autoHeight: {
          height: ''
        },
      }
    },
    methods: {
      getHeight() {
        this.autoHeight.height = (windowHeight - 110) + 'px';
      },
    },
    created() {
        window.addEventListener('resize', this.getHeight)
        this.getHeight()
      },
      destroyed() {
        window.removeEventListener('resize', this.getHeight)
      }
  }
</script> 

2. 说明

  • div动态绑定style样式, 如autoHeight
<template>
  <div :style="autoHeight"></div>
</template>
  • 获取浏览器高度后,经过计算后赋值
  let windowHeight = parseInt(window.innerHeight)
  export default {
    data() {
      return {
        windowHeight: windowHeight,
        autoHeight: {
          height: ''
        },
      }
    },
   methods: {
      getHeight() {
        this.autoHeight.height = (windowHeight - 110) + 'px';
      },
    },
  • created生命周期中,监听浏览器的变化
 created() {
        window.addEventListener('resize', this.getHeight)
        this.getHeight()
      },
 destroyed() {
        window.removeEventListener('resize', this.getHeight)
      }

3. window下的各种宽高度

  • window.innerWidth
    文档显示区(body)的宽度

  • window.innerHeight
    文档显示区(body)的高度

  • window.outrWidth
    窗口的宽度(body+任务栏)

  • window.outerHeight
    窗口的高度(body+任务栏)

  • window.pageYOffset
    文档左上角到文档显示区左上角的距离

  • screen.width
    分辨率的宽度

  • screen.height
    分辨率的高度

  • screen.availWidth
    去掉任务栏剩余分辨率宽度

  • screen.availHeight
    去掉任务栏剩余分辨率高度

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。