javascript - 在 pre 或 div 标签中设置指针位置

标签 javascript html pre

如何设置指针位置? 我尝试了该主题中最著名的解决方案: Set keyboard caret position in html textbox 但这个解决方案仅适用于输入......

这是代码:

$(document).ready(function(){
	$("#asd").keypress(function(){
		//set cursor to a position
	})
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head><body>

<pre id="asd" contenteditable="true" >
asd
</pre>

</body>
</html>

最佳答案

像这样:

function setCursor(pos) {
    var el = document.getElementById("asd");
    var range = document.createRange();
    var sel = window.getSelection();
    range.setStart(el.childNodes[0], pos);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
    el.focus();
}

$(document).ready(function(){
	$("#asd").keypress(function(){
		setCursor(4);
	})
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head><body>

<pre id="asd" contenteditable="true" >
asd
two
</pre>

</body>
</html>

关于javascript - 在 pre 或 div 标签中设置指针位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40794506/

相关文章:

javascript - 类似于 Facebook 评论框的富文本框

javascript - 我使用 document.getelementsbyclassname 是否错误?

html - 调整窗口大小时从左下角制作背景图像 "grow"

jquery - 奇怪的行为 - jQuery .html() 导致 IE8 中 <pre> 元素中的换行符丢失

带有跨浏览器换行符的 Javascript 预格式化文本

javascript - 如何删除部分 HTML

javascript - Angular2 嵌套 formGroups - formArrays 和模板绑定(bind)

c# - 将 C# 数据结构传递给 javascript

jQuery - 如果不在 Web 服务器上则无法加载

html - 如何用左尖括号 'pre' 解决 '<' 标签的问题?