如何在可内容元素(Div)中设置插入符号(游标)位置?我以这个简单的HTML为例:<div id="editable" contenteditable="true">
text text text<br>
text text text<br>
text text text<br></div><button id="button">focus</button>我想要简单的事情-当我点击按钮时,我想把插入符号(光标)放在可编辑的div中的特定位置。从网上搜索,我有这个JS附在按钮点击,但它不工作(FF,Chrome):var range = document.createRange();var myDiv = document.getElementById("editable");range.setStart(myDiv, 5);range.setEnd(myDiv, 5);是否可以像这样手动设置插入符号的位置?
3 回答
皈依舞
TA贡献1851条经验 获得超3个赞
function createRange(node, chars, range) { if (!range) { range = document.createRange() range.selectNode(node); range.setStart(node, 0); } if (chars.count === 0) { range.setEnd(node, chars.count); } else if (node && chars.count >0) { if (node.nodeType === Node.TEXT_NODE) { if (node.textContent.length < chars.count) { chars.count -= node.textContent.length; } else { range.setEnd(node, chars.count); chars.count = 0; } } else { for (var lp = 0; lp < node.childNodes.length; lp++) { range = createRange(node.childNodes[lp], chars, range); if (chars.count === 0) { break; } } } } return range;};
function setCurrentCursorPosition(chars) { if (chars >= 0) { var selection = window.getSelection(); range = createRange(document.getElementById("test").parentNode, { count: chars }); if (range) { range.collapse(false); selection.removeAllRanges(); selection.addRange(range); } }};
function isChildOf(node, parentId) { while (node !== null) { if (node.id === parentId) { return true; } node = node.parentNode; } return false;};function getCurrentCursorPosition(parentId) { var selection = window.getSelection(), charCount = -1, node; if (selection.focusNode) { if (isChildOf(selection.focusNode, parentId)) { node = selection.focusNode; charCount = selection.focusOffset; while (node) { if (node.id === parentId) { break; } if (node.previousSibling) { node = node.previousSibling; charCount += node.textContent.length; } else { node = node.parentNode; if (node === null) { break } } } } } return charCount;};
陪伴而非守候
TA贡献1757条经验 获得超8个赞
public setCaretPosition() { const editableDiv = document.getElementById('contenteditablediv'); const lastLine = this.input.nativeElement.innerHTML.replace(/.*?(<br>)/g, ''); const selection = window.getSelection(); selection.collapse(editableDiv.childNodes[editableDiv.childNodes.length - 1], lastLine.length);}
editableDiv
id
innerHTML
添加回答
举报
0/150
提交
取消