在移动端开发中提交表单,苹果端显示正常,但是在安卓上显示异常,顶起键盘会让输入框顶到莫名其妙的位置。本文旨在解决这种怪异的样式问题。

定义初始高度

1
2
3
4
5
6
7
data(){
return {
screenHeight: document.body.clientHeight, // 这里是给到了一个默认值
originHeight: document.body.clientHeight, // 默认高度在watch里拿来做比较
isOriginHei: true // 这个属性是固定定位按钮的显隐开关(需要就加,不需要隐藏)
}
}

created里面判断类型

1
2
3
4
5
6
7
8
9
10
11
const ua = navigator.userAgent;
const self = this;
if (ua.indexOf("Android") > -1 || ua.indexOf("Adr") > -1) {
this.platform = "android";
window.onresize = () => {
return (() => {
// 获取视图变化时屏幕高度
self.screenHeight = document.body.clientHeight;
})();
};
}

watch监听视图变化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

watch: {
screenHeight(val) {
// 判断软键盘弹出,收起
const that = this;
if (this.originHeight - val > 50) {
// 键盘弹出
that.$nextTick(() => {
const y = that.$refs[that.dom].offsetTop - 80;
document.body.scrollTop = y;
document.documentElement.scrollTop = y;
window.scrollTo(0, y);
});
} else {
// 键盘收起
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
window.scrollTo(0, 0);
}
}
}