vue项目动态获取窗口以及元素宽高

场景1:页面刚进来时,获取窗口的默认宽高以及某个元素(div)的默认宽高

场景2:当页面缩放时,自动获取窗口的宽高以及某个元素(div)的宽高

 效果如下:

 因为不喜欢看别人写那么多废话,只想直接看代码,因为我有很完善的注释

<template>
    <div class="document">
        <strong>动态获取页面窗口及元素宽高</strong>
        <div>
            <p class="red">页面窗口默认宽度为:{
   
   {windowWidth}}</p>
            <p class="red">页面窗口默认高度为:{
   
   {windowHeight}}</p>
        </div>
        <div class="temp" ref="Temp">
            <p>此元素的宽度是:{
   
   {tempWidth}}</p>
            <p>此元素的高度是:{
   
   {tempHeight}}</p>
        </div>
    </div>
</template>

<script>
export default {
    data(){
        return{
            windowWidth:0,//页面窗口宽度
            windowHeight:0,//页面窗口高度
            tempWidth:0,//元素宽度
            tempHeight:0,//元素高度
        }
    },
    mounted(){
        var that = this;
        //刚进入页面时,获取窗口默认宽高度
        this.windowWidth = document.body.clientWidth
        this.windowHeight = document.body.clientHeight

        //进入页面元素默认宽高
        this.tempWidth = this.$refs.Temp.offsetWidth
        this.tempHeight = this.$refs.Temp.offsetHeight
        //根据屏幕缩放自动获取页面宽高
        window.onresize = () => {
            return (() => {
                //窗口缩放自动获取页面宽高
                window.fullWidth = document.documentElement.clientWidth;
                window.fullHeight = document.documentElement.clientHeight;
                that.windowWidth = window.fullWidth; //宽
                that.windowHeight = window.fullHeight; //高

                //窗口缩放自动获取元素宽高
                this.tempWidth = this.$refs.Temp.offsetWidth //宽
                this.tempHeight = this.$refs.Temp.offsetHeight //高
            })()
        }
    },
    watch:{
        windowHeight (val) {
            let that = this;
            console.log("实时屏幕高度:",val, that.windowHeight);
        },
        windowWidth (val) {
            let that = this;
            console.log("实时屏幕宽度:",val, that.windowWidth);
        }
    }
}
</script>

<style scoped>
    .document{height:100%;}
    html,body{height:100%;font-size:30px;}
    .red{color:red;font-weight:600;}
    p{}
    .temp{width:80%;height:40%;background:red;}
</style>

猜你喜欢

转载自blog.csdn.net/qq_17211063/article/details/127915697
今日推荐