JS/Vue动态获取浏览器高度

本文介绍如何使用JavaScript和Vue动态获取浏览器高度,以实现页面布局的动态调整。通过原生JS的onresize事件及Vue组件的生命周期钩子,结合节流函数优化,确保在浏览器尺寸变化时流畅地更新页面布局。

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

原文地址:https://www.jeremyjone.com/448/, 转载请注明

动态获取浏览器大小,可以动态调整页面布局,让页面更加灵活。

JS获取浏览器高度:
var width=document.documentElement.clientWidth;
var height=document.documentElement.clientHeight;

原生JS动态获取浏览器大小改变使用onresize

window.onresize = function(){
    alert(document.documentElement.clientHeight);
}

Vue组件中动态获取高度,使用如下方式

首先在data中声明height变量:

data() {
  return {
    height: `${document.documentElement.clientHeight}`,
  }
},

如果需要在初始化有一些操作,可以在created中实现:

created() {
  this.windowHeight(document.documentElement.clientHeight);
},

当组件挂载后,调用JS的onresize方法:

mounted() {
  const _this = this;
  window.onresize = () => {
    return (() => {
	  // 可以在这里保存到浏览器中,也可以保存到其他地方
      // window.height = document.documentElement.clientHeight;
      // _this.height = window.height;
      _this.height = `${document.documentElement.clientHeight}`;
    })();
  };
},

watch中监听高度变化,这里优化了监听间隔,使用setTimeout,每500ms监听一次,这样操作避免了浏览器大小在持续变化时,连续监听带来的卡顿现象:

watch: {
  height (val) {
    if(!this.timer) {
      this.height = val
      this.timer = true
      let _this = this
      setTimeout(function () {
        _this.timer = false
      }, 500)
    }
    // 这里可以添加修改时的方法
    this.windowHeight(val);
  }
},

定义上面修改时具体的操作方法:

methods: {
  windowHeight: function (value) {
      // do something...
  }
},

这样就可以实现监听浏览器大小的改变。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值