1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > js让光标定位在文本的最后位置

js让光标定位在文本的最后位置

时间:2020-01-18 17:55:39

相关推荐

js让光标定位在文本的最后位置

有时候用focus好像不管用,它定位跑到了文字的最前面。我们想把它放在最后面怎么办呢?

<divcontenteditable="true" id="text"></div>

//让光标定位在最后

setFocus(el) {

el = el[0]; // jquery 对象转dom对象

el.focus();

var range = document.createRange();

range.selectNodeContents(el);

range.collapse(false);

var sel = window.getSelection();

//判断光标位置,如不需要可删除

if(sel.anchorOffset!=0){

return;

};

sel.removeAllRanges();

sel.addRange(range);

}

调用:setFocus($("#text"));

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。