天天看點

vue中動态設定内外div的布局,鍵盤彈出時動态變高度

一、鍵盤彈起時頁面局部異常問題。

<template>
    <div id="div1" class="result"  ref="container" >

        <div id="div2" :style="{marginTop: marginTop}">
            <van-sticky :container="container" >
            頁面内容
              </van-sticky>
        </div>
    </div>
</template>
           
<style>
    .result{
        background:url("url位址");
        min-height: 500px;
        width:100%;
        height:100%;
        position:fixed;
        background-size:100% 100%;}

    #div2 {
        margin:0 auto;width:280px;height:40px;
    }
</style>

<script>
    export default {
        components: {},
        data() {
            return {
                container: null,
                marginTop: null,
            };
        },
        mounted() {
            this.container = this.$refs.container;
            const originalHeight = document.documentElement.clientHeight ||document.body.clientHeight;
            window.onresize = ()=>{
                return(()=>{
                    //鍵盤彈起與隐藏都會引起視窗的高度發生變化
                    const resizeHeight=document.documentElement.clientHeight || document.body.clientHeight;
                    //console.log("進入到判斷頁面高度=========");
                    //console.log("頁面初始高度========="+originalHeight);
                    //console.log("軟鍵盤彈起高度========="+resizeHeight);
                    if(resizeHeight-0<originalHeight-0){
                        //當軟鍵盤彈起,在此處操作
                        //console.log("進入到軟鍵盤彈起=========");
                        //document.querySelector('result').setAttribute('style', 'height:'+originalHeight+'px;');
                        this.marginTop='80%';
                    }else{
                        //當軟鍵盤收起,在此處操作
                        //console.log("進入到軟鍵盤收起=========");
                        //document.querySelector('result').setAttribute('style', 'height:100%;');
                        this.marginTop="120%";
                    }
                })()

            }
        },
        // 解決安卓手機調出來軟鍵盤,螢幕背景被擠壓的問題
        created() {
            // 擷取目前可視區域的高度
            const height = document.documentElement.clientHeight;
            // 在頁面整體加載完畢時
            window.onload = function () {
                // 把擷取到的高度指派給父div
                document.getElementById('div1').style.height = `${height}px`;
            };
        },
        methods: {  
        },
    };
</script>
           

二、頁面不需要鍵盤彈起的情況下。

在main.js檔案裡面引入擷取螢幕的元件

Vue.prototype.$getViewportSize = function(){
  return {
    width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,//相容性擷取螢幕寬度
    height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight//相容性擷取螢幕高度
  };
};
           

在頁面的created方法中設定内div距離外div的距離。this.$getViewportSize()可以擷取螢幕的寬高。

created() {
    const distance = this.$getViewportSize().height * 0.6;
    this.marginTop = distance+"px";
},
           

繼續閱讀