工作中是做sns开发的,然后一天一个js focus定位挺有意思的,特把代码贴出来分享下,基于easyTalk的。
<html>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<script src="jquery-1.7.1.js"></script>
<script>
$(document).ready(function(){
setCaretPosition('ceshi', '3');
//第三个参数是设置结束的位置,如果开始和结束的位置都给,就是选中那段文字了。
});
function setCaretPosition(div, pos1, pos2) {
var textArea = document.getElementById(div);
if (document.selection) { //ie
var rng = textArea.createTextRange();
rng.collapse(true);
//rng.moveEnd("character",pos2);
rng.moveStart("character",pos1);
rng.select();
} else if (textArea.selectionStart || (textArea.selectionStart == '0')) { // Mozilla/Netscape…
textArea.selectionStart = pos1;
//textArea.selectionEnd = pos2;
}
textArea.focus();
}
</script>
<body>
<textarea id="ceshi">钓鱼岛是中国的!苍井空是全世界的!</textarea>
</body>
</html>
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/98522.html