不带下拉列表的<p>标签上的自动完成建议

时间:2019-03-15 06:24:33

标签: javascript jquery

我正在尝试对内容可编辑的段落标记进行自动填充(无下拉菜单)。在用户键入时如何使用javascript / jQuery在contenteditable p标签中选择剩余的建议字母?

enter image description here

// On typing
$(document).on('input', '.cell-input', function(e) {
    var userInput = e.target.innerText;

    // Suggested 'Bond' to user, because user typed (assumption) 'B'
    e.target.innerText = 'Bond';

    // Select
    $(e.target).selectText(1, 3);
});

// To select
jQuery.fn.selectText = function(startPos, endPos){
    var doc = document;
    var element = this[0];

    if (doc.body.createTextRange) {
        var range = document.body.createTextRange();
        range.moveToElementText(element);
        range.select();
    }
    else if (window.getSelection) {
        var selection = window.getSelection();        
        var range = document.createRange();
        range.selectNodeContents(element);
        selection.removeAllRanges();
        selection.addRange(range);
    }
};

全选工作正常。然后我尝试添加:

selection.moveEnd("character", endPos);
selection.moveStart("character", startPos);

range.moveEnd("character", endPos);
range.moveStart("character", startPos);

..但没有运气。我的方向正确吗?请指教。

1 个答案:

答案 0 :(得分:0)

使用setStart()setEnd()

$(document).on('input', '.cell-input', function(e) {
  var userInput = e.target.innerText;

  // Suggested 'Bond' to user, because user typed (assumption) 'B'
  e.target.innerText = 'Bond';

  // Select
  $(e.target).selectText(1, 4);
});

// To select
jQuery.fn.selectText = function(startPos, endPos) {
  var doc = document;
  var element = this[0];

  if (doc.body.createTextRange) {
    var range = document.body.createTextRange();
    range.moveToElementText(element);
    range.select();
  } else if (window.getSelection) {
    var selection = window.getSelection();
    var range = document.createRange();
    range.setStart(element.firstChild, startPos);
    range.setEnd(element.firstChild, endPos);
    selection.removeAllRanges();
    selection.addRange(range);
  }
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p class="cell-input" contenteditable="true">B</p>

注意:使用element.firstChild可能不适用于HTML子节点