---
title: "IE支持的JS的TextRange和selection对象"
author: "arlwei"
date: "2012-08-10T16:18:27Z"
tags: []
categories: ["Web前端"]
slug: "ie-js-textrange-selection"
draft: false
lastmod: "2012-08-11T16:48:53Z"
id: 1628418
url: "https://arlwei.iteye.com/blog/1628418"
---

TextRange对象仅仅IE浏览器支持，Chrome和FF都不支持。

利用TextRange对象，我们可以实现一些与文本有关的任务。比如说，定位，查找。

可以利用createTextRange()方法为input、textarea、body等创建TextRange。例如: var tr = document.body.createTextRange();

TextRange主要的方法有：

1、move相关的：moveStart("UNIT"\[,count]);moveEnd("UNIT"\[,count]);move("UNIT"\[,count]);

moveStart();默认开始为TextRange对象的第一个字符

moveEnd();默认开始为TextRange对象的最后一个字符

它们配合起来可以选中特定的区域。

move();可以将光标移动到TextRange的某一位置。

UNIT取值范围为CHARACTER(字符)、WORD(词)、SENTENCE(段落)、textedit。

\[,count]可正可负，代表相对于当前位置的偏移量。

2、选择查找相关：

select();选择moveStart();和moveEnd();之间的内容

collapse(boolean b);重叠插入点。true代表从开始处重合，反之则结尾处重合。

findText("search string"\[,search scope,flags]);search scope指的是搜索的范围，值越大，范围越大，若值为负，则从反向搜索。flags代表是否大小写敏感。2代表匹配整个单词,4代表大小写敏感。

 

 

document.selection只有IE支持，window.getSelection()也只有FireFox和Safari支持，都不是标准语法。selection 对象代表了当前激活选中区，即高亮文本块，或文档中用户可执行某些操作的其它元素。selection 对象的典型用途是作为用户的输入，以便识别正在对文档的哪一部分正在处理，或者作为某一操作的结果输出给用户。

 

 

 

光标定位至起始位置

 

```
function locatePoint(){ 
var aCtrl = document.getElementById("txtContent"); 
if (aCtrl.setSelectionRange) { 
setTimeout(function() { 
aCtrl.setSelectionRange(0, 0); //将光标定位在textarea的开头，需要定位到其他位置的请自行修改 
aCtrl.focus(); 
}, 0); 
}else if (aCtrl.createTextRange) { 
var textArea=document.getElementById("txtContent"); 
var tempText=textArea.createTextRange(); 
tempText.moveEnd("character",0-tempText.text.length); 
tempText.select(); 
} 
} 
```

 

这段代码来自：[http://www.jb51.net/article/26527.htm](http://www.jb51.net/article/26527.htm)

 

其他相关资料：[http://w3help.org/zh-cn/causes/SD9031](http://w3help.org/zh-cn/causes/SD9031)

     [http://blog.csdn.net/wayne23/article/details/1248925](http://blog.csdn.net/wayne23/article/details/1248925)

     [http://blog.163.com/wr\_asdf/blog/static/42930451200911252735453/](http://blog.163.com/wr_asdf/blog/static/42930451200911252735453/)