您当前位置: 首页 » web前端 » JavaScript » web前端 » contenteditable 自动获取光标且光标定位到最后的方法

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

2016年2月17日 | 蒙奇·D·撸码客 发表评论(0) 查看评论

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();
}

}

});


JavaScript,web前端内容推荐

发表评论?

0 条评论。

发表评论