私はiOS用のリッチテキストエディターに取り組んでおり、ほとんどが機能していますが、ユーザーが入力を開始したときにカーソルがビューポートに表示されるようにするという無限の問題が発生しています。
私は斬新なアプローチを思いつきました: カーソル位置にスパンを挿入し、スパンまでスクロールしてから削除します。(スパンが画面上にある場合にのみスクロールすることはできませんでした。) ここに私が書いたものがあります:
document.addEventListener('keypress', function(e) {
jumpToID();
}, false);
function jumpToID() {
var id = "jumphere2374657";
var text = "<span id='" + id + "'> </span>"
document.execCommand('insertHTML', false, text);
var element = document.getElementById(id);
element.scrollIntoView();
element.parentNode.removeChild(element);
}
これで問題なく動作する場合もあれば、キーを押すたびに非ブレーク スペースを残して <span></span> タグのみを削除する場合もあります。何か案は?誰かに提案があれば、これを行うためのより良い方法を受け入れます。カーソルを表示するのがいかに難しいか少しショックを受けましたが、JS は初めてです。
編集
これは機能するコードです:
var viewportHeight = 0;
function setViewportHeight(vph) {
viewportHeight = vph;
if(viewportHeight == 0 && vph != 0)
viewportHeight = window.innerHeight;
}
function getViewportHeight() {
if(viewportHeight == 0)
return window.innerHeight;
return viewportHeight;
}
function makeCursorVisible() {
var sel = document.getSelection(); // change the selection
var ran = sel.getRangeAt(0); // into a range
var rec = ran.getClientRects()[0]; // that we can get coordinates from
if (rec == null) {
// Can't get coords at start of blank line, so we
// insert a char at the cursor, get the coords of that,
// then delete it again. Happens too fast to see.
ran.insertNode( document.createTextNode(".") );
rec = ran.getClientRects()[0]; // try again now that there's text
ran.deleteContents();
}
var top = rec.top; // Y coord of selection top edge
var bottom = rec.bottom; // Y coord of selection bottom edge
var vph = getViewportHeight();
if (top < 0) // if selection top edge is above viewport top,
window.scrollBy(0, top); // scroll up by enough to make the selection top visible
if (bottom >= vph) // if selection bottom edge is below viewport bottom,
window.scrollBy(0, bottom-vph + 1); // scroll down by enough to make the selection bottom visible
}
viewportHeight は、Web アプリの場合よりも複雑です。モバイル アプリの場合、キーボードを考慮する必要があるため、viewportHeight を手動で設定する方法と、window.innerHeight からの自動設定の方法を提供します。