1. 鍵盤彈出觸發window.resize,對頁面產生擠壓,造成定位紊亂
在頁面初始化完成的時候,固定外部容器的寬高,resize的時候也不影響內部dom的相對位置。例如,以body為容器:
<style type="text/css">
html,body{
width: 100%;
height: 100%;
margin: 0;
box-sizing: border-box;
}
body{
position: relative;
overflow-y: scroll;
scroll-behavior:smooth;
-webkit-overflow-scrolling: touch;
}
</style>
<script>
document.addEventListener('DOMContentLoaded',function(){
var fullWidth = window.screen.width;
var fullHeight = window.screen.height;
if(document.documentElement && document.documentElement.clientHeight){
fullWidth = document.documentElement.clientWidth;
fullHeight = document.documentElement.clientHeight;
}
document.body.style.width = fullWidth + "px";
document.body.style.height = fullHeight + "px";
false);
</script>
2. 鍵盤彈出時,輸入框被遮擋在鍵盤下面
1) 監聽resize事件,計算位置並滾動頁面到一定距離。例如:
window.onresize = function(){
// 計算輸入框離窗口頂部的距離
var toTop = document.activeElement.getBoundingClientRect().top;
// 滾動頁面 使輸入框距離頂部100px
window.scrollTo({
top: document.documentElement.scrollTop + (toTop - 100),
behavior: "smooth"
});
}
2) scrollIntoView方法
window.onresize = function(){
// 滾動 使輸入框處在窗口的中間高度
document.activeElement.scrollIntoView({
behavior:"smooth",
block :"center"
})
}
3. 定義安卓客戶端的鍵盤行為
不是所有的app在鍵盤彈出的時候都會造成頁面的resize,因為客戶端程序可以定義鍵盤彈出是否影響窗口的大小。
在安卓項目中,設置對應activity的SoftInputMode為 adjustPan|stateHidden,這樣鍵盤彈出時就會覆蓋窗口,而不會擠壓窗口造成變形。
