removeChild之有时删除整个跨度,有时不(removeChild sometimes rem

2019-08-01 04:41发布

我正在为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);
}

在某些情况下,这工作得很好,并在某些情况下,它的叶子每次按键之间的非休息空间,删除<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自动设置。

Answer 1:

我不知道这是否会在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. 获得大选
  2. getRangeAt
  3. getClientRects
  4. scrollBy


文章来源: removeChild sometimes removes entire span and sometimes doesn't