我正在尝试对内容可编辑的段落标记进行自动填充(无下拉菜单)。在用户键入时如何使用javascript / jQuery在contenteditable p标签中选择剩余的建议字母?
// 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);
..但没有运气。我的方向正确吗?请指教。
答案 0 :(得分:0)
$(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子节点