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

时间:2016-11-24 21:07:58

标签: 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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

像这样:

&#13;
&#13;
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);
	})
});
&#13;
<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>
&#13;
&#13;
&#13;