Home  >  Article  >  Web Front-end  >  Summary of how to use textRange object in JavaScript

Summary of how to use textRange object in JavaScript

伊谢尔伦
伊谢尔伦Original
2016-11-24 10:18:321314browse

TextRange object is an advanced feature of dynamic HTML (DHTML). It can be used to achieve many text-related tasks, such as searching and selecting text. Text ranges allow you to selectively pick characters, words, and sentences out of a document. The TextRange object is an abstract object that establishes the start and end positions on the text stream that the HTML document will display.

The following are the commonly used properties and methods of TextRange:

Properties

boundingHeight Gets the height of the rectangle bound to the TextRange object

boundingLeft Gets the distance between the left edge of the rectangle bound to the TextRange object and the left side of the containing TextRange object

offsetLeft Gets the calculated left position of the object relative to the layout or the parent coordinate specified by the offsetParent property

offsetTop Gets the calculated top position of the object relative to the layout or the parent coordinate specified by the offsetParent property

htmlText Gets the rectangle bound to the TextRange object The width of

text Set or get the text contained in the range

Methods

moveStart Change the start position of the range

moveEnd Change the end position of the range

collapse Move the insertion point to the beginning or end of the current range

move collapse Given a text range and moves the empty range the given number of units

execCommand Execute a command on the current document, current selection, or given range

select Set the current selection to the current object

findText Search for text in the text and Sets the start and end points of the range to surround the search string.

Using TextRange objects usually involves three basic steps:

1. Create a text range

2. Set the start and end points

3. Operate the range

<script language="javascript"> 
function moveCursor() 
{ 
    var temp = this.txtNum.value;  
    if(isNaN(temp)) 
    { 
     alert("请输入一个数字"); 
     return; 
    } 
    var rng = this.txtTest.createTextRange(); 
    rng.move("character",temp); 
    rng.select();    
}  
</script> 
</HEAD> 
<BODY> 
<input type="text" name="txtTest" value="明·罗贯中《三国演义》第二十一回 操曰:“夫英雄者,胸怀大志,腹有良谋,有包藏宇宙之机,吞吐天地之志者也。" size="100"><br> 
移动光标到第<input type="text" name="txtNum" size="5">个位置 
<input type="button" name="btnMove" value="移动" onclick="moveCursor()">  
</BODY>

1. createTextRange()

Create a TextRange objects, BODY, TEXT, TextArea, BUTTON and other elements all support this method. This method returns a TextRange object.

2.move("Unit"[,count])

The move() method performs two operations. First, the method overlaps the current document at the previous end point and uses this as an insertion point; next, it moves the insertion point forward or backward by any number of characters, words, or sentence units. The first parameter of the

method is a string, and the units it specifies include character, word, sentence, and textedit. The textedit value moves the insertion point to the end of the entire text range (no parameters required). If the first three units are specified, the default value is 1 when the parameter is ignored. You can also specify an integer value to indicate the number of units. A positive number represents moving forward, and a negative number represents moving backward.

Note that the ranges still overlap after the move() method is executed.

3.select()

select() method selects the text within the current text range. The display cursor here must also be implemented using it, because the so-called "cursor" can be understood as the range where the boundaries overlap

<BODY> 
<textarea name="txtBox" rows="7" cols="50" id="txtBox"> 
菊花台 (满城尽带黄金甲主题曲)  
歌手:周杰伦 专辑:依然范特西  
 
你的泪光 柔弱中带伤  
惨白的月弯弯 勾住过往  
夜太漫长 凝结成了霜  
是谁在阁楼上冰冷的绝望  
雨轻轻淌 朱红色的窗  
我一生在纸上 被风吹乱  
梦在远方 化成一缕霞  
随风飘散 你的模样  
 
菊花惨淡地伤 你的笑容已泛黄  
花落人断肠 我心事静静淌  
北风乱夜未央 你的影子剪不断  
徒留我孤单在湖面生霜  
</textarea><br> 
<input type="text" value="输入要查询的内容" id="txtFind"> 
<input type="button" value="查找下一个" onclick="findText(txtFind.value)"> 
<script language="javascript"> 
var rng = txtBox.createTextRange(); 
function findText(str) 
{ 
   if(str=="") 
   return; 
   //定义一个变量,作为moveStart()函数的偏移量,即开始点跳过选择文本 
   var num = 0; 
   if(document.selection)    
     num = document.selection.createRange().text.length; 
       //每次调用函数,结束点都为末尾,而开始点是跳过选择文本后的新开始点  
       rng.moveStart("character",num); 
       rng.moveEnd("character",txtBox.value.length); 
       //搜索到后选择文本    
   if(rng.findText(str)) 
    rng.select(); 
   //搜索到最后的范围还是找不到,则提示搜索完毕,并重新恢复rng最初的范围(否则无法执行新搜索)    
   if(rng.text!=str) 
   {    
       alert("搜索完毕"); 
       rng = txtBox.createTextRange(); 
   } 
}    
</script>  
</BODY>

The above The example demonstrates the use of moveStart() and moveEne() methods to select a range. The descriptions of several methods that appear are as follows:

4. moveStart("Unit"[,count]) and moveEnd("Unit"[,count])

The moveStart() and moveEnd() methods are similar to the move() method. By default, the starting point is the first character of the container and the end point is the last character.

We can modify the above selectText() function to prove:

function selectText()
{
  var rng = txtBox.createTextRange();
  rng.moveStart("character",1);
  rng.moveEnd("character",-1);
  rng.select();
}

Move the start point forward by one character and the end point backward by one character. After running, you can see that the selected range is the entire text range except the first character and the last character.

5.collapse([Boolean])

You can use the collapse() method to overlap the text range from the current size to a single insertion point between characters. The optional parameter of the collapse() method is a Boolean value, which indicates whether the range overlaps at the beginning or end of the current range. The default value is true, which coincides with the starting point:

6.findText("searchString"[,searchScope,flags])

One of the most useful methods of the TextRange object is the findText() method, whose default behavior is from the starting point to The end point browses the text range, searching for a case-insensitive string match. If an instance is found in the range, the start and end points of the range are placed in this text, and the method returns true; otherwise, it returns false, and the start and end points remain unchanged. The method only searches the display text, not any tags or attributes.

The optional parameter searchScope is an integer value that indicates the number of characters from the starting point. The larger the value, the more text is included in the search range; a negative value will force the search operation to search backward from the current starting point.

可选参数flag用来设置搜索是否区分大小写,或者是否仅匹配整个单词。参数是整数值,它用按位组合的数学方法计算单个值,这些值能容纳一个或多 个设置。匹配整个单词的值为2;匹配大小写的值为4;如果只想匹配一项,则只提供希望的值就够了,但对于两种行为,要用位操作XOR操作符(^操作符)使 值为6。

findText()方法最常用的应用包括范围中的查找和替换操作,以及格式化一个字符串的实例,因为搜索通常以范围的当前开始点开始,所以再次 查询要将开始点移到范围中匹配文本的末尾(如示例3),移动后才能使findText()继续浏览剩下的文本范围,来查找另一个匹配。可以使用 collapse(false)方法迫使开始点移动第一个匹配的范围的结束点。所以示例3的findText()函数也可以修改为:

<script language="javascript">
 
var rng = txtBox.createTextRange();
 
function findText(str)
{
    if(str=="")
    return;
 
    if(rng.findText(str))
   {
     rng.select();
   rng.collapse(false);
     }
    //搜索到最后的范围还是找不到,则提示搜索完毕,并重新恢复rng最初的范围(否则无法执行新搜索)  
    else
     {  
     alert("搜索完毕");
     rng = txtBox.createTextRange();
     }
}  
 
</script>

6.parentElement()

parentElement()方法返回包含文本范围容器的引用

获得光标选中文本的DOM对象

<script> 
function getParElem() 
{ 
    var rng = document.selection.createRange(); 
    var container = rng.parentElement(); 
    //alert(container.getAttribute("id")||container.getAttribute("value")||container.getAttribute("type")); 
    alert(container.tagName); 
} 
</script> 
</HEAD> 
 
<BODY> 
 
这是只属于Body的文本 
<div>这是包含在div里的文本</div> 
<p>这是包含在p里面的文本</p> 
<div><strong>这是包含在div->strong里的文本</strong></div> 
<input type="button" value="选择文本后点击" onClick="getParElem()"> 
</BODY>

   


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn