window.onresize的使用

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

window.onresize的使用

清虚桂意   2022-06-03 我要评论

window.onresize的使用

说下重点

window.onresize只能在一个组件中使用,如果多个组件调用则会出现覆盖情况,所以我的解决方案是在App.vue中使用,获取document.documentElement.clientWidth(即浏览器宽度)存放在vuex中,别的组件只需要用computed(计算属性)将vuex的clientWidth获取,然后通过watch监听clientWidth的值,即可触发组件事件

App.vue代码

<script>
export default {
  name: 'app',
  mounted () {
    window.onresize = () => {
      this.clientWidthResize()
    }
  },
  methods: {
    clientWidthResize () {
      this.$store.commit('Tool/resizeWidth', Number(document.documentElement.clientWidth))
    }
  }
}
</script>

store中tool.js代码(此处进行模块化开发)

export default {
  namespaced: true,
  state: {
    clientWidth: 0
  },
  getters: {},
  mutations: {
    resizeWidth(state, clientWidth) {
      state.clientWidth = clientWidth;
    },
  },
  actions: {},
}

组件使用

computed: {
  clientWidth () {
    return this.$store.state.Tool.clientWidth || Number(document.documentElement.clientWidth)
  }
},
watch: {
  clientWidth (val) {
    console.log(val)
  }
},

window.onresize笔记

1.浏览器尺寸变化响应事件

 window.onresize = function(){....}

这里需要注意的是,onresize响应事件处理中,获取到的页面尺寸参数是变更后的参数。

// 获取到的是变更后的页面宽度
var currentWidth = document.body.clientWidth; 

如果需要使用到变更之前的参数,需要建一个全局变量保存之前的参数(并且记得在onresize事件中刷新这个全局变量保存新的参数值)。

2.谷歌浏览器中

window.onresize事件默认会执行两次(偶尔也会只执行一次,网上大部分说法认为这是Chrome的bug)。

解决方法:

一般来说推荐新建一个标志位 延时复位控制它不让它自己执行第二次,代码如下:

var firstOnResizeFire = true;//谷歌浏览器onresize事件会执行2次,这里加个标志位控制
 
window.onresize = function()
{
 if (firstOnResizeFire) {
  NfLayout.tabScrollerMenuAdjust(homePageWidth);
  firstOnResizeFire = false;
  
  //0.5秒之后将标志位重置(Chrome的window.onresize默认执行两次)
  setTimeout(function() {
   firstOnResizeFire = true;
        }, 500);
 } 
 homePageWidth = document.body.clientWidth; //重新保存一下新宽度
}

3.页面尺寸变更事件

注意要分为尺寸增大和尺寸变小两个方向考虑。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们