移動(dòng)端業(yè)務(wù)開發(fā),iOS 下經(jīng)常會(huì)有 fixed 元素和輸入框(input 元素)同時(shí)存在的情況。 但是 fixed 元素在有軟鍵盤喚起的情況下,會(huì)出現(xiàn)許多莫名其妙的問題。 這篇文章里就提供一個(gè)簡(jiǎn)單的有輸入框情況下的 fixed 布局方案。
iOS下的 Fixed + Input BUG現(xiàn)象
// html
<body class="layout-fixed">
<!-- fixed定位的頭部 -->
<header>
</header>
<!-- 可以滾動(dòng)的區(qū)域 -->
<main>
<!-- 內(nèi)容在這里... -->
</main>
<!-- fixed定位的底部 -->
<footer>
<input type="text" placeholder="Footer..."/>
<button class="submit">提交</button>
</footer>
</body>
// css如下
header, footer, main {
display: block;
}
header {
position: fixed;
height: 50px;
left: 0;
right: 0;
top: 0;
}
footer {
position: fixed;
height: 34px;
left: 0;
right: 0;
bottom: 0;
}
main {
margin-top: 50px;
margin-bottom: 34px;
height: 2000px
}
問題描述: 軟鍵盤喚起后,頁面的 fixed 元素將失效(即無法浮動(dòng),也可以理解為變成了 absolute 定位),所以當(dāng)頁面超過一屏且滾動(dòng)時(shí),失效的 fixed 元素就會(huì)跟隨滾動(dòng)了。
條件:
- 頁面使用原生滾動(dòng)(body);
解決方案:
- 使用iscroll等第三方庫布局方案;
- 不使用原生滾動(dòng)(body);
// 不使用原生滾動(dòng)(body);
header, footer, main {
display: block;
}
header {
position: fixed;
height: 50px;
left: 0;
right: 0;
top: 0;
}
footer {
position: fixed;
height: 34px;
left: 0;
right: 0;
bottom: 0;
}
main {
/* main絕對(duì)定位,進(jìn)行內(nèi)部滾動(dòng) */
position: absolute;
top: 50px;
bottom: 34px;
/* 使之可以滾動(dòng) */
overflow-y: scroll;
-webkit-overflow-scrolling: touch;
}
main .content {
height: 2000px;
}
擴(kuò)展閱讀:
overflow-scrolling,will-change等屬性會(huì)觸發(fā)新的層疊上下文。
啟用GPU硬件加速的屬性。
transform對(duì)普通元素的N多渲染影響
- 影響層疊上下文
- 影響元素的fixed的跟隨效果
- 影響元素的參照物
- z-index,opactiy值不為1,transform不是none,will-change