---
title: "js设置光标选中text中指定文字"
author: "xiaodi667"
date: "2012-12-13T13:11:32Z"
tags: []
categories: ["Web前端"]
slug: "js-text"
draft: false
lastmod: "2012-12-13T13:11:32Z"
id: 1747052
url: "https://xiaodi667.iteye.com/blog/1747052"
---

```java

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>

<body>
<textarea id="o"></textarea>
<input type="button" value="aaaa" onclick="setSelectText(document.getElementById('o'),3,5)" />
<script>
function setSelectText(el,start,end){
	if(el.createTextRange){
		var Range=el.createTextRange();
		Range.collapse();
		Range.moveEnd('character',end);
		Range.moveStart('character',start);
		Range.select();
	}
if(el.setSelectionRange){
        el.focus();  
        el.setSelectionRange(start,end);  //设光标 
    }
}
</script>
</body>
</html>


```