js设置光标始终在文本最后(亲测可行)

JavaScript012

js设置光标始终在文本最后(亲测可行),第1张

利用contenteditable=”true”模拟输入框时,focus()方法会将光标定位在文本的首位,需要将光标挪到最后一位

传入当前标签的节点对象(jquery对象)例: $("#addInput") ;

会经常遇到选择后可编辑div中的光标不见了,或者显示的位置不对,现在总结下:

function set_focus()

{

el=document.getElementById('guestbook_editor')

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

el.focus()

if($.support.msie)

{

var range = document.selection.createRange()

this.last = range

range.moveToElementText(el)

range.select()

document.selection.empty()//取消选中

}

else

{

var range = document.createRange()

range.selectNodeContents(el)

range.collapse(false)

var sel = window.getSelection()

sel.removeAllRanges()

sel.addRange(range)

}

}

调用此方法,可以将光标放在可编辑div的最后。

<html xmlns=" http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/htmlcharset=utf-8" />

<title>无标题文档</title>

<script language="javascript">

function aa(){

var textNode=document.getElementById("con")//获取你的文本域

var count=textNode.value.length//统计文本域里面有多少个字符了,注意留空不行额

var a = textNode.createTextRange()//创建文本范围对象a

a.moveStart('character',count) //更改范围起始位置

a.collapse(true) //将插入点移动到当前范围的开始或结尾。

a.select() //将当前选中区置为当前对象,执行

}

</script>

</head>

<body>

<img src="em_01.gif" onclick="aa()" />

<form name="form1" action="" method="post">

<textarea name="message" id="con" cols="70" rows="50">上的花费时间恢复速度发生大幅公共空间豆腐干</textarea>

</form>

</body>

</html>