在html中加入文本框,在html文本框中设置键盘插入符的位置

A generic function that will allow you to insert the caret at any position of a textbox or textarea that you wish:

function setCaretPosition(elemId, caretPos) {

var elem = document.getElementById(elemId);

if(elem != null) {

if(elem.createTextRange) {

var range = elem.createTextRange();

range.move('character', caretPos);

range.select();

}

else {

if(elem.selectionStart) {

elem.focus();

elem.setSelectionRange(caretPos, caretPos);

}

else

elem.focus();

}

}

}

The first expected parameter is the ID of the element you wish to insert the keyboard caret on. If the element is unable to be found, nothing will happen (obviously). The second parameter is the caret positon index. Zero will put the keyboard caret at the beginning. If you pass a number larger than the number of characters in the elements value, it will put the keyboard caret at the end.

Tested on IE6 and up, Firefox 2, Opera 8, Netscape 9, SeaMonkey, and Safari. Unfortunately on Safari it does not work in combination with the onfocus event).

An example of using the above function to force the keyboard caret to jump to the end of all textareas on the page when they receive focus:

function addLoadEvent(func) {

if(typeof window.onload != 'function') {

window.onload = func;

}

else {

if(func) {

var oldLoad = window.onload;

window.onload = function() {

if(oldLoad)

oldLoad();

func();

}

}

}

}

// The setCaretPosition function belongs right here!

function setTextAreasOnFocus() {

/***

* This function will force the keyboard caret to be positioned

* at the end of all textareas when they receive focus.

*/

var textAreas = document.getElementsByTagName('textarea');

for(var i = 0; i < textAreas.length; i++) {

textAreas[i].onfocus = function() {

setCaretPosition(this.id, this.value.length);

}

}

textAreas = null;

}

addLoadEvent(setTextAreasOnFocus);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值