在webView 編輯中,對(duì)于鍵盤遮擋是一個(gè)非常頭疼的事情,一般做法有:
一、采用控制 WebView 可視區(qū)域與鍵盤的高度關(guān)系,并實(shí)時(shí)的滑動(dòng) WebView
注:原始空間 frame 變化頻繁,容易在復(fù)雜UI情況下照常 controller邏輯過于復(fù)雜
二、通過JS獲取光標(biāo)位置,并計(jì)算與WebView坐標(biāo)位置,然后與鍵盤高度的關(guān)系進(jìn)行換算
注:換算過程容易造成WebView 抖動(dòng)問題
三、純粹通過 JS 控制光標(biāo)顯示位置,通過JS 實(shí)現(xiàn)window滑動(dòng)
經(jīng)過多個(gè)方案實(shí)現(xiàn)比較,方案三實(shí)現(xiàn)存儲(chǔ) JS控制,容易維護(hù),并且效果是最優(yōu)的一種。
WebView 設(shè)置可編輯
contenteditable 是將html中某一標(biāo)簽設(shè)置成可編輯狀態(tài),允許調(diào)起鍵盤輸入內(nèi)容
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
${script}
</head>
<body style="margin:0px;background:#FFFFFF">
<div id="main" style="padding-left:10px; margin-left:10px;margin-right:10px;font-size:16px" contenteditable="true">
${content}
</div>
</body>
</html>
避免鍵盤遮擋
1、通過 JS 監(jiān)聽 input 輸入事件,每一次自動(dòng)調(diào)整window滑動(dòng)位置
2、獲取光標(biāo)位置,采用臨時(shí)插入 <span>標(biāo)簽,獲取其坐標(biāo),然后在從父節(jié)點(diǎn)將其刪除。
注:
- 在正常字符輸入,獲取當(dāng)前光標(biāo)位置可以通過
var sel = document.getSelection(); // change the selection
var ran = sel.getRangeAt(0); // into a range
var rec = ran.getClientRects()[0];
var top = rec.top; // Y coord of selection top edge
var bottom = rec.bottom; // Y coord of selection bottom edge
var left = rec.left; // X coord of selection left edge
var right = rec.right; // X coord of selection right edge
-
但是在輸入換行符時(shí),該方法就無法實(shí)現(xiàn)準(zhǔn)確獲取坐標(biāo)位置了,只能通過取巧的方式,臨時(shí)插入 <span>標(biāo)簽 的方法
var gCursorOffset = 200;
function setCursorOffset(offset) {
// 設(shè)置光標(biāo) 相對(duì)于頂部 的偏移量
if (offset > 0 ) {
gCursorOffset = offset;
}
}
// 獲取當(dāng)前光標(biāo)的位置坐標(biāo)
function getCursorPosition() {
var sel = window.getSelection();
var range = sel.getRangeAt(0);
var span = document.createElement('span');
range.collapse(false);
range.insertNode(span);
var topPosition = span.offsetTop;
var spanParent = span.parentNode;
spanParent.removeChild(span);
// spanParent.normalize();
return topPosition;
}
function autoScroll(y)
{
var position = getCursorPosition();
console.log('position: ' + position);
window.scrollTo(0,position - gCursorOffset);
}
// 監(jiān)聽輸入事件
document.addEventListener("input", function(e){
autoScroll();
},false);
