contenteditable 自动获取光标且光标定位到最后的方法

contenteditable 自动获取光标且光标定位到最后的方法

<div id=”contenteditable” contenteditable=true>web前端</div>

$(“#contenteditable”).on(“click”,function(){
if($(this).attr(“contenteditable”)==’false’){//不加这个判断的话,无论怎么样点,光标都在最后,这样就会导致无法把光标手动定位到你想要的位置
$(this).attr(“contenteditable”,true);
if (window.getSelection) {//ie11 10 9 ff safari
$(this).focus(); //解决ff不获取焦点无法定位问题
var range = window.getSelection();//创建range
range.selectAllChildren($(this)[0]);//range 选择obj下所有子内容
range.collapseToEnd();//光标移至最后
}else if (document.selection) {//ie10 9 8 7 6 5
var range = document.selection.createRange();//创建选择对象
range.moveToElementText($(this)[0]);//range定位到obj
range.collapse(false);//光标移至最后
range.select();
}

}

});

未经允许不得转载:前端撸码笔记 » contenteditable 自动获取光标且光标定位到最后的方法

上一篇:

下一篇: