【博学谷学习记录】超强总结 用心分享|前端学习w23- resize事件监听窗口变化

1,138 阅读2分钟

今天复习一下resize 事件

resize 事件是在浏览器窗口大小发生变化时触发,利用该事件可以跟踪窗口大小的变化来动态调整页面的元素显示。

接下来利用 resize 事件实现一个小案例:监听浏览器窗口变化,实时获取该窗口的宽度和高度。 实现 首先写一个获取窗口宽高的方法

const getWindowInfo = () => {
	const windowInfo = {
		width: window.innerWidth,
		hight: window.innerHeight
	}
	console.log(windowInfo);
};

然后监听 resize 事件

window.addEventListener('resize', getWindowInfo);

这样就已经简单实现了,不过这种方式会导致触发方法的频率很高

image.png 这个时候就需要防抖,无论我们怎么拖动窗口大小,只执行一次获取浏览器宽高的方法

const debounce = (fn, delay) => { let timer; return function() { if (timer) { clearTimeout(timer); } timer = setTimeout(() => { fn(); }, delay); } }; const cancalDebounce = debounce(getWindowInfo, 500);

window.addEventListener('resize', cancalDebounce); 现在就可以了,该方法只会在窗口停止变化的 500 毫秒后触发一次

友情提示:如果是在 vue 中使用的话,记得在组件销毁的钩子中去移除监听事件,不然可能会出现一些你意想不到的 bug

window.removeEventListener('resize', cancalDebounce);

方法一:

First-step : 定义变量

data(){
  return{
     formLabelWidth : '123px'
  }
},

Second-step:   根据生命周期 在mounted 中绑定 窗口变化

 mounted(){
       const that = this
       window.onresize = () => {
         return (() => {
          window.screenWidth = document.body.clientWidth
          that.screenWidth = window.screenWidth
         })()
       }
 },

Third-step:   绑定监听 watch

watch: {
       screenWidth (val) {
            if (!this.timer) {
              this.screenWidth = val
              this.timer = true
              let that = this
              setTimeout(function () {
                // that.screenWidth = that.$store.state.canvasWidth
                console.log(that.screenWidth)
                // that.init()
                that.timer = false
              }, 400)
            }
       }
 },

方法二:在vue.2x里面时候,mounted 里面可以直接挂载 window.onresize事件。全局监听

 mounted(){
       window.onresize = () => {
         return (() => {
           this.handleLableWidth();
         })()
       }
       this.handleLableWidth();
},

完全可以做到检测窗口变化

created() {
    //浏览器放大缩小事件
    this.$nextTick(() => {
      this.resizeFun();
      // this.resizeFun窗口变化执行的方法
      window.addEventListener("resize", this.resizeFun);
    });
  },

(2)

methods: {
    // 监听浏览器放大缩小的事件
    resizeFun() {
      // 窗口变化执行的操作
      var windowNum = window.devicePixelRatio;
      console.log(windowNum);
      if (windowNum > 1) {
         //这里写入执行条件
      } else {
        //这里写入执行条件
      }
    },
  },

(3)

beforeDestroy() {
    //离开页面时删除该监听
   window.removeEventListener("resize", this.resizeFun);
  },

在mounted中写下:

在页面初始化时,window.onresize 来监听浏览器窗口的变化。在变化时,调用函数,或者直接写业务逻辑。

window.onresize = () => {
      return (() => {
        this.$nextTick(() => {
          this.headHeight();
        });
      })();
    };

(created()的时候不行,因为此时document还没有生成)

在methods中写下:

可以使用js内置的window、document等相关函数获取页面或者盒子的尺寸。

headHeight() {
      // 页面可视高度
      let pageInnerHeight = window.innerHeight;// 搜索框高度
      let divOffsetHeight =
        document.getElementsByClassName("divStyle")[0].offsetHeight;
      console.log(pageInnerHeight, divOffsetHeight);
    },
  },
import { mapActions } from 'vuex' import { throttle } from '@/utils' export default { data () { return { handler: () => {}, win: null } }, mounted () { this.win = window this.resize() this.handler = throttle(this.resize, 300) this.win.addEventListener('resize', this.handler) }, methods: { ...mapActions(['setScale']), resize () { let scale = this.win.innerWidth / this.win.__BASE_WIDTH__ // 该判断用于处理点击f11全屏后scale不变导致watch不到scale变化的问题 scale === this.win.scale && (scale += 0.00001) this.win.scale = scale this.setScale(scale) } }, beforeDestroy () { this.win.removeEventListener('resize', this.handler) } }
```
<template>
    <div >

    </div>
</template>
<script>

    export default {
        data() {
            return {
                screenWidth: style="color:rgb(98 189 255)">document.style="color:rgb(98 189 255)">documentElement.clientWidth,//屏幕宽度
                screenHeight: style="color:rgb(98 189 255)">document.style="color:rgb(98 189 255)">documentElement.clientHeight,//屏幕高度
            }
        },
        watch:{
            'screenWidth':function(val){ //监听屏幕宽度变化
                var style="color:rgb(253 97 106)">oIframe = style="color:rgb(98 189 255)">document.getElementById(divId);
                style="color:rgb(253 97 106)">oIframe.style.width = (Number(val)-120) + 'px'; //'120'是页面布局调整,可去除

            },
            'screenHeight':function(){ //监听屏幕高度变化
                var style="color:rgb(253 97 106)">oIframe = style="color:rgb(98 189 255)">document.getElementById(divId);
                style="color:rgb(253 97 106)">oIframe.style.height = (Number(val)-120) + 'px'; //'120'是页面布局调整,可去除
            }
        },
        mounted() {
            var _this = this;
            window.onresize = function(){ // 定义窗口大小变更通知事件
                _this.screenWidth = style="color:rgb(98 189 255)">document.style="color:rgb(98 189 255)">documentElement.clientWidth; //窗口宽度
                _this.screenHeight = style="color:rgb(98 189 255)">document.style="color:rgb(98 189 255)">documentElement.clientHeight; //窗口高度
            };
        }
    }
</script>