---
title: "textarea光标位置插入文字"
author: "deng131"
date: "2011-06-18T18:14:20Z"
tags: []
categories: ["Web前端"]
slug: "textarea"
draft: false
lastmod: "2011-06-18T18:14:48Z"
id: 1097494
url: "https://thinking80s.iteye.com/blog/1097494"
---

各浏览器TextArea获得焦点后的光标位置情况：

textarea.focus()
FireFox: 所有文字结束处
IE: 文字开头
Opera: 文字开头
Chrome: 文字开头
Safari: 文字开头

IE支持document.selection，Firefox，Chrome,Safari以及Opera都有selectionStart和selectionEnd属性。

针对浏览器的特性进行判断并实现，代码如下：

```java
function insertText(obj,str) {
	if (document.selection) {
		var sel = document.selection.createRange();
		sel.text = str;
	} else if (typeof obj.selectionStart === 'number' && typeof obj.selectionEnd === 'number') {
		var startPos = obj.selectionStart,
			endPos = obj.selectionEnd,
			cursorPos = startPos,
			tmpStr = obj.value;
		obj.value = tmpStr.substring(0, startPos) + str + tmpStr.substring(endPos, tmpStr.length);
		cursorPos += str.length;
		obj.selectionStart = obj.selectionEnd = cursorPos;
	} else {
		obj.value += str;
	}
}
function moveEnd(obj){
	obj.focus();
	var len = obj.value.length;
	if (document.selection) {
		var sel = obj.createTextRange();
		sel.moveStart('character',len);
		sel.collapse();
		sel.select();
	} else if (typeof obj.selectionStart == 'number' && typeof obj.selectionEnd == 'number') {
		obj.selectionStart = obj.selectionEnd = len;
	}
｝
```


参考：
<http://foxling.org/js-ajax-dom/cross-browser-cursor-position-in-textarea/>