天天看点

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";
},
           

继续阅读