Range:文本框选区学习笔记

分类:Pure Javascript 发表时间:2010年11月22日 字体大小:12号14号

有一段时间没有看《Javascript高级程序设计》了,最近重新接着看起,发现新的两个勘误,已经提交给为之漫笔了。

昨晚看到了文本框选区跨浏览器处理的部分。之前参加的交流会上,Taobao的前端分享过他们的Editor,主要的技术也是Range的应用。Range主要还是用在即见即所得Editor中,本文纯粹是做笔记之用,为避免以后自己遇到这样的需求而到处搜索,不如在自己的Blog上做个标记。

也做了个Demo页面,有兴趣的可以点击了查看效果。

download demo

一、Html代码:

1
2
3
4
5
6
7
8
9
<ul>
	<li><input type="text" value="Hello World!" id="textbox" name="textbox" size="50" /></li>
 
    <li><input type="button" id="getSelectedBtn" value="getSelectedText" /></li>
 
    <li><label for="startIndex">开始位置:</label><input type="text" size="5" id="startIndex" name="startIndex" />&nbsp;&nbsp;&nbsp;&nbsp;<label for="stopIndex">结束位置:</label><input type="text" size="5" id="stopIndex" name="endIndex" /></li>
 
	<li><input type="button" id="selectBtn" value="selectText" /></li>
</ul>

二、Javascript代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
var textbox = document.getElementById('textbox'),
	getSelectedBtn = document.getElementById('getSelectedBtn'),
	selectBtn = document.getElementById('selectBtn');
 
function getSelectedText(textbox) {
	if(document.selection) {
		return document.selection.createRange().text;
	} else { //IE
		return textbox.value.substring(textbox.selectionStart, textbox.selectionEnd);
	};
}
 
function selectText(textbox) {
	var startIndex = document.getElementById('startIndex').value, 
		stopIndex = document.getElementById('stopIndex').value;
	if(textbox.setSelectionRange) {
		textbox.setSelectionRange(startIndex, stopIndex);
	} else if(textbox.createTextRange) { //IE
		var range = textbox.createTextRange();		//创建范围
		range.collapse(true);				//折叠预选取范围到开始位置
		range.moveStart('character', startIndex);		//将预选取范围的起点和终点移动到相同的位置
		range.moveEnd('character', stopIndex - startIndex);		//选取字符长度
		range.select();			//选取范围
	alert(stopIndex);
	}
	textbox.focus();
}
 
getSelectedBtn.onclick = function() {
	alert(getSelectedText(textbox));
};
selectBtn.onclick = function() {
	selectText(textbox);
};

不错不错,已经有 个评论!
  1. 好好学习下
    技术钻研得挺深啊

  2. 去看了下demo,才明白是怎么回事。

    • 我想做前端的一眼就可以看出是什么回事,其他的人看不明白很正常的!

  3. 搜藏起来 给哥哥看

  4. 谢谢你的分享~

  5. 好文章,支持下

  6. very good~xm138.com.cn

  7. 楼主写的很不错,没有多余的修饰,文章也显得容易理解。总体感觉很有可读性。顶你一个。欢迎回访哦~

    • 就是要简单易懂才好嘛,呵呵!

  8. 近期也在学习中。。

  9. 正想学习

  10. 嗯,厉害,学习了,哈,我是学.NET的

  11. 不错啊,一起学习。

  12. 博客很给力 加油

  13. 来学习了 感谢博主分享

  14. 技术多多交流谢谢分享哈