removeChild有时会删除整个范围,有时则不会

时间:2012-10-04 23:04:17

标签: javascript ios uiwebview removechild

我正在开发一个用于iOS的富文本编辑器,并且大部分都在工作,但遇到了无穷无尽的问题,确保在用户开始输入时光标在视口中可见。

我提出了一种新颖的方法:在光标位置插入一个跨度,滚动到跨度,然后将其删除。 (如果跨度在屏幕上,我还没有滚动。)这是我写的:

document.addEventListener('keypress', function(e) {            
   jumpToID();
}, false);

function jumpToID() {
  var id = "jumphere2374657";
  var text = "<span id='" + id + "'>&nbsp;</span>"
  document.execCommand('insertHTML', false, text);
  var element = document.getElementById(id);
  element.scrollIntoView();
  element.parentNode.removeChild(element);
}

在某些情况下,这种方法很好,在某些情况下,它会在每次按键之间留下一个不间断的空格,删除&lt; span&gt;&lt; / span&gt;仅标签。有任何想法吗?如果有人有建议,我愿意接受更好的方法。我对使光标显示有多困难感到有点震惊,但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中的自动设置。

1 个答案:

答案 0 :(得分:2)

我不知道这是否适用于iOS,但如果光标的位置意味着此时有一个选择..

function moveToSelection(){
    var sel = document.getSelection(), // change the selection
        ran = sel.getRangeAt(0),       // into a range
        rec = ran.getClientRects()[0], // that we can get co-ordinates from
        dy  = rec.top;                 // distance to move down/up
    window.scrollBy( 0, dy );          // actual move

    // console.log( sel, ran, rec, y );   // help debug
}

moveToSelection();

相关链接

  1. getSelection
  2. getRangeAt
  3. getClientRects
  4. scrollBy