<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
<style>
html,body{
width:100%;
height:100%;
margin:0;
padding:0;
}
.box{
display:flex;
flex-direction:column;
width:100%;
height:100%;
}
.header{
height:50px;
width:100%;
background:#368CDA;
text-align:center;
line-height:50px;
font-size:20px;
color:#fff;
}
.wrapper{
flex:1;
overflow:auto;
width:100%;
}
.content {
margin:0;
padding:0;
}
.content li{
margin:0;
padding:0;
list-style:none;
height:150px;
background:#FFCC99;
text-align:center;
line-height:150px;
font-size:20px;
color:#fff;
}
.content li:nth-child(2n){
background:#CC99CC
}
.t-input{
width:300px;
height:50px;
border:1px solid #FF0000;
}
.footer{
width:100%;
height:48px;
background: #368CDA;
text-align:center;
line-height:48px;
font-size:18px;
color:#fff;
}
</style>
</head>
<body>
<div class="box">
<div class="header">頭部</div>
<div class="wrapper">
<ul class="content">
<li>內容區</li>
<li>內容區</li>
<li>內容區</li>
<li>內容區</li>
<li>內容區</li>
</ul>
<input type="text" class="t-input" placeholder="輸入框">
</div>
<div class="footer">保存</div>
</div>
</body>
</html>
<style>
.box{
/*
display:flex;
flex-direction:column;
*/
width:100%;
height:100%;
position:relative;
}
.wrapper{
/*
flex:1;
*/
overflow:auto;
width:100%;
// 經過同時設置top、bototm,撐開wrapper,使之佔屏幕除header和footer外的剩餘高
position:absolute;
top:50px;
bottom:48px;
}
.footer{
width:100%;
height:48px;
background: #368CDA;
text-align:center;
line-height:48px;
font-size:18px;
color:#fff;
position:absolute;
bottom:0;
}
</style>
3.真機模擬:進行真機與電腦鏈接調試,打開chrome的chrome://inspect,(以下圖所示),發現鍵盤未彈出時html高度爲512px,鍵盤彈出後html的高度爲288px(減小區域的爲軟鍵盤區域),懷疑是不是由於html、body設置了height:100%的自適應佈局後,高度跟隨屏幕的可用高度改變而改變致使的。
4.代碼調試:去除body的height:100%,給body添加一個正好能讓軟鍵盤彈出後遮住輸入框的高度,body高度 = 288(軟鍵盤出現後html高度)+50(輸入框高度)+48(保存按鈕高度) ,發現鍵盤彈出遮擋着input後,input框會自動上移到可視區內,問題定位成功。
解決方案:
方案1 頁面渲染完成後,經過JS動態獲取屏幕可視區高度(注:屏幕旋轉後,需從新獲取屏幕高度並賦值),並將其賦值到body的height,這樣body的高度一直都是屏幕的高度,當軟鍵盤彈出後,會將body向上推(由於body有了固定高度,不會再繼承html的自適應高度),使輸入框置到可視區內,代碼以下:
document.body.style.height = window.screen.availHeight +'px';
方案2 咱們能夠藉助元素的 scrollIntoViewIfNeeded() 方法,這個方法執行後若是當前元素在可視區中不可見,則會滾動瀏覽器窗口或容器元素,最終讓它可見,若是當前元素在可視區中,這個方法什麼也不作,代碼以下: