JavaScript中文本光标定位

本文介绍了在不同浏览器中实现光标定位的方法,包括IE、Firefox和Chrome等,并提供了JavaScript代码示例,展示了如何获取和设置光标位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载地址:http://levi.cg.am/archives/1448


项目中客户要求选择商品后,光标直接定位到数量输入框上,来简化操作。

document.getElementById(“cargoCount”).focus();//定位光标到数量框
还有需求涉及到定位到第几位字段上。

1
2
3
4
5
6
7
function setMouse(){
var e = event.srcElement;
var r = e.creatTextRange();
r.moveStart( 'character' ,2);
r.collapse( true );
r.select();
}

在IE浏览器下使用是createTextRange而Firefox/chrome等浏览器下使用setSelectionRange

IE:

1
2
3
4
var range = obj.createTextRange();
range.moveStart( "character" , 开始序号);
range.moveEnd( "character" , 结束序号);
range.select();

FF:

1
2
obj.setSelectionRange(开始序号, 结束序号);
obj.focus();

 

  1. //DOM Level 2中定义了方法creatRange()来创建范围
  2. var oRange = document.createRange();
  3. DOM下selectNode和selectNodeContent方法
  4. <p id=”id1″><b>Hello</b>World</p>
  5. var oRange1 = document.createRange();
  6. var oRange2 = document.createRnage();
  7. var oP1 = document.getElementById(“id1″);
  8. oRange1.selectNode(oP1);
  9. oRange2.selectNodeContents(oP1);

selectNode()获取到的oRange1是<p id=”id1″><b>Hello</b>World</p>
selectNodeContent()获取到的oRange2是<b>Hello</b>World

 

参考:
http://hi.baidu.com/wangjiashui/blog/item/da1e4e6eabbe96dc80cb4a29.html
http://www.zhangxinxu.com/wordpress/?p=755
http://blog.csdn.net/qiaogang2003/archive/2007/11/06/1870025.aspx

 

javascript获取光标位置以及设置光标位置

在项目开发中经常遇到input等设置光标位置到最后的问题,今天我查了一下Google,找到了在IEFirefoxOpera等主流浏览器的获取光标位置(getCursortPosition)以及设置光标位置(setCursorPosition)的函数。

function getCursortPosition (ctrl) {//获取光标位置函数
	var CaretPos = 0;	// IE Support
	if (document.selection) {
	ctrl.focus ();
		var Sel = document.selection.createRange ();
		Sel.moveStart ('character', -ctrl.value.length);
		CaretPos = Sel.text.length;
	}
	// Firefox support
	else if (ctrl.selectionStart || ctrl.selectionStart == '0')
		CaretPos = ctrl.selectionStart;
	return (CaretPos);
}

 

PS:参数ctrl为input或者textarea对象

 

function setCaretPosition(ctrl, pos){//设置光标位置函数
	if(ctrl.setSelectionRange)
	{
		ctrl.focus();
		ctrl.setSelectionRange(pos,pos);
	}
	else if (ctrl.createTextRange) {
		var range = ctrl.createTextRange();
		range.collapse(true);
		range.moveEnd('character', pos);
		range.moveStart('character', pos);
		range.select();
	}
}

PS:参数ctrl为input或者textarea对象,pos为光标要移动到的位置。

 

jQuery中光标定位

$(“#siteUrl”).val(‘http://’);
$(“#siteUrl”).focus();

IE6下光标会定位在前面:

image

而将两行代码换过来:

$(“#siteUrl”).focus();
$(“#siteUrl”).val(‘http://’);

IE6下光标会定位在后面:

image



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值