vue 监听屏幕可视区域宽度 动态设置弹窗位置

1、监听屏幕可视宽度:

data(){
    return{
        showWidth:0,  //屏幕可视宽度
    }
}

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

注意点:

        1、mounted中定义的屏幕宽度变化时才会重新获取,即window.onresize,所以在页面初始化的时候是不会获取屏幕宽度来改变showWidth的初始值的;想要在初始化的时候也获取屏幕宽度,只需要在created中插入语句:【this.showWidth = document.body.clientWidth】即可。

2、动态设置弹窗位置

<div :style=" showWidth < 1370 ? { top: '-66px' , left: '-160px' } : { top: '-66px' , left: '99px' }) " class="move-popup" >
      <h5>确认进行本次操作吗?</h5>
      <div class="btn">
           <button @click.stop="handleCancel">取消</button>
           <button @click.stop="handleConfirm">确定</button>
      </div>
 </div>

.move-popup{
    position: absolute;
    width: 160px;
    height: auto;
}

写法:

        将整个确认框设置成定位,然后通过内联样式,在不同的视口宽度下,设置不同的top和left值,就能实现动态的弹窗位置了。(利用f12可以自测不同屏幕宽度下的弹窗位置状况。)

 

 

猜你喜欢

转载自blog.csdn.net/m0_48571414/article/details/126957862