移动端H5 input输入完成后页面底部留白问题
五星人 · 342浏览 · 发布于2021-06-07
说明
最近在用
vue
写几个H5页面在微信上展示,遇到一个在弹窗上input
输入完成之后点击键盘的完成,页面底部留出一片空白的问题
出现原因分析
当键盘抬起时,
window.scrollY
会从0变到键盘的高度,所以解决办法就是当input
失去焦点的时候,将window.scrollY
重新设置为0
解决
给所有的
input``textarea
组件设置获取焦点和设置焦点事件,失去焦点的时候将``window.scrollY`设置为0因为的是
vue
所以结合vue
来写代码
<template> <input class="m-input" :value="value" @input="$emit('input', $event.target.value)" @focus="inputFocus()" @focusout="inputFocusOut"> </template> <script> export default { name: "MInput", props:['value'], data(){ return{ timer:null } }, methods:{ inputFocus(){ if(this.timer){ clearTimeout(this.timer) } }, inputFocusOut(){ this.timer = setTimeout(() => { window.scrollTo(0,0) },10) } }, destroyed(){ if(this.timer){ clearTimeout(this.timer) } } } </script>
获取焦点事件,判断定时器是否存在如果存在的话清除掉(上一个input设置的定时器)
失去焦点事件,将
window.scrollY
设置为0
,并且给一个10
的定时器,减少页面失去焦点的突兀感(为了顺滑一点点)destroyed
vue
组件中如果使用了定时器,一定要记得在组件销毁的生命周期里将清时期清除掉,防止全局定时器过多,容易爆栈
补充:解决方案2
在input上分别增加
focus
和blur
的方法,基本可以解决键盘回落后留白问题;
handleFocus(event) { let e = event.currentTarget; setTimeout(() => { e.scrollIntoView({ block: 'start', behavior: 'smooth' }); }, 300); } handleblur() { let e = event.currentTarget; setTimeout(() => { e.scrollIntoView({ block: 'end', behavior: 'smooth' }); }, 300); window.scrollTo(0, 0); }
补充:解决方案3
//解决键盘弹出后挡表单的问题 window.addEventListener('resize', function() { if( document.activeElement.tagName === 'INPUT' || document.activeElement.tagName === 'TEXTAREA' ) { window.setTimeout(function() { if('scrollIntoView' in document.activeElement) { document.activeElement.scrollIntoView(); } else { document.activeElement.scrollIntoViewIfNeeded(); } }, 0); } });
补充:页面来回弹跳
问题:失焦时的scrollTop=0造成的页面弹跳。本来iOS是做了这方面的优化,在软键盘弹出和收起时页面会smooth的平滑,由于我加了scrollIntoView破坏了原生的优化导致弹跳了
解决:
handleFocus(event) { clearTimeout(this.timer); } handleblur() { this.timer = setTimeout(() => { document.body.scrollTop = 0; window.pageXOffset = 0; document.documentElement.scrollTop = 0; }, 100); }
作者:w候人兮猗
链接:https://www.jianshu.com/p/c8f3a4036251
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
相关推荐
android下vulkan与opengles纹理互通
talkchan · 1177浏览 · 2020-11-23 10:37:39
Android 使用RecyclerView实现轮播图
奔跑的男人 · 2175浏览 · 2019-05-09 17:11:13
微软发布新命令行工具 Windows Terminal
吴振华 · 869浏览 · 2019-05-09 17:15:04
在华为写了十几年代码,我为什么还没有被拿去“祭天”
追忆似水年华 · 1201浏览 · 2019-05-09 17:22:20
android 通过修改图片像素实现CircleImageView
吴振华 · 1127浏览 · 2019-05-09 22:26:56
分类专栏
最新发布
最热排行
0评论