zoukankan      html  css  js  c++  java
  • 随时监测屏幕大小,解决手机端小键盘遮挡输入框问题

    为什么?  

      为什么要随时监测屏幕大小,这是因为我们在手机端的时候,常常会遇到这样的问题:当点击输入框的时候,手机的键盘就会自动浮现,它会使得页面的可视示高度(document.body.clientHeight)发生变化。而我们的输入框就被可怜的遮挡在小键盘后面

    怎么办?

      我们不知道小键盘何时会出现,但有一点是可以确定的,当小键盘出现的时候,body的可视区域一定为发生变化!!当我们检测到页面的可视高度发生了变化,我们就可以确定手机的键盘出来了。于是我们就可以使用document.getElementById('×××××').scrollIntoView();把被小键盘遮挡住的输入框给上移到可视区域。

    Ps:结合scrollIntoView()使用的还有activeElement当我们页面有多个input输入框时,我们可以使用HTML5的辅助管理DOM功能,document.activeElement属性始终会引用DOM当前获得的焦点元素。可以获得当前用户焦点的元素。

    document.activeElement.scrollIntoView();
    

    监测手机小键盘弹出代码:

    window.onresize = () => {
        // 注意,return返回的函数为立即执行函数!!
        return (() => {
            window.screenHeight = document.body.clientHeight;
            this.showHeight = window.screenHeight;
        })()
    }

    当我拿到showHeight,在vue里,我就可以通过watch他的变化,然后再执行相应的逻辑代码,使用Vue.js完整代码如下:

    data() {
        return {
            // 默认屏幕高度
            docmHeight: document.documentElement.clientHeight,
            showHeight: document.documentElement.clientHeight,
        }
    // 渲染后执行
    mounted() {
        window.onresize = () => {
            return (() => {
                window.screenHeight = document.body.clientHeight;
                this.showHeight = window.screenHeight;
            })()
        }
    },
    watch: {
        showHeight: 'inputType',
    },
    methods: {
        // 检测屏幕高度变化
        inputType() {
             if (!this.timer) {
                 this.timer = true
                 let that = this
                 setTimeout(() => {
                     if (that.docmHeight > that.showHeight) { 
                         that.inputfile = false;
                         if (document.activeElement.className === 'weui-textarea') {
                             document.getElementById('applyNote').scrollIntoView(); // 输入框的id为applyNote,class为weui-textarea
                         }
                     } else if (that.docmHeight <= that.showHeight) {
                         that.inputfile = true;
                     }
                     that.timer = false;
                 }, 20)
            }
        }
    }
    不安逸,不浮躁,牛B就是一个学习累积的过程
  • 相关阅读:
    Android推送通知指南
    proteus ISIS学习笔记
    总结ACM 中的基本输入输出
    WINDOWS远程默认端口3389的正确修改方式
    SQL还原数据库后孤立用户问题处理(SQL 数据库 拥有对象 无法删除)
    利用计划任务定时备份Express2005数据库
    使用 bcompiler 给PHP代码加密编译
    Discuz X2.5 编辑DIY数据出现:Unknown column 'pid' in 'where clause' 的解决办法
    批处理解决SqlServer自动备份与自动清理7天以前的备份
    PHP去除全角空格与空白字符
  • 原文地址:https://www.cnblogs.com/pengshengguang/p/7765079.html
Copyright © 2011-2022 走看看