Using the TextRange Object

2016-02-19 12:05 3 1 收藏

想不想get新技能酷炫一下,今天图老师小编就跟大家分享个简单的Using the TextRange Object教程,一起来看看吧!超容易上手~

【 tulaoshi.com - Web开发 】

Most users will only want to use the innerText/innerHTML and outerText/outerHTML properties and methods discussed previously. However, there is some more advanced text manipulation that can be done using a "text range" object. The TextRange object can be used to:  Locate the text for a given element or a given point.
Search for words and characters in the text of the document.
Move through the text in logical units.
Provide read/write access to the plain text and the HTMLText in the document.
This feature might not be available on non- Microsoft Win32 platforms. For the latest information on Microsoft Internet Explorer cross-platform compatibility, see article Q172976 in the Microsoft Knowledge Base.
This article consists of the following topics:

Overview of the TextRange Object
What Do I Do with a TextRange Object?
Positioning the TextRange Object
Creating a TextRange Object
Getting the Content of a TextRange
Comparing Ranges
Commands
Overview of the TextRange Object
Text range objects are an advanced feature of Dynamic HTML (DHTML) that you can use to carry out useful tasks related to dynamic content, such as searching for and selecting text. Text ranges let you selectively pick out characters, words, and sentences from a document. The TextRange object is an abstract object that creates a start and end position over the stream of text that would appear in the HTML document. Consider the following simple HTML document: 

HTML
BODY
H1Welcome/H1
CENTERH2OverviewH2/CENTER
PBe sure to BRefresh/B this page./P
/BODY
/HTML
In this document, creating a text range over the body element would position the start at the beginning of the textual content of the body, and the end at the end of the textual content of the body. This text range would contain the plain text "Welcome Overview Be Sure to Refresh this page." 

What Do I Do with a TextRange Object?
There are two parts to manipulating text with a TextRange object. The first is to create a text range so that the start and end positions encompass the desired text. The next step is to apply a method to the text range, or make a copy of the text to be used elsewhere in the document. Once the text range is positioned, you can search for text, select the text, and make a copy of the text and use it elsewhere in your document. 

See the TextRange object in the Object Model Reference for the properties and methods supported. 

Positioning the TextRange Object
Each text range has a start and an end position defining the scope of the text that is encompassed by the TextRange object. When you create a new text range, the start and end positions encompass the entire content by default. Use methods such as move, moveStart, and moveEnd to change the scope of the text range. 

Other methods can position the TextRange object with respect to a particular element, or a point on the page. For example, moveToElementText positions the text range so that it encompasses the text contained by the given element. The moveToPoint method positions the text range at a given point where the user clicked a mouse button. The x and y positions of the user's click are known by the window.event object and can be used to position the range over a given point. From this collapsed point, the range can then be expanded to encompass a word, sentence, or a whole textEdit (the entire possible TextRange object). 

Show Example

HTMLHEAD
TITLEmoveToPoint Example/TITLE
script
    function selectMe() {
    var r=document.body.createTextRange();
    r.moveToPoint(window.event.x, window.event.y);
    r.expand("word");
    r.select();
    }
/script
/HEAD
BODY

H1 id=myH1 onclick=selectMe()Click on a word and it will highlight/H1

/BODY/HTML
Show Me
Creating a TextRange Object
You create a TextRange object by applying the createTextRange method to a body, textArea, or button element. You can also create a text range from a selection made by the user. The createRange method on the selection object returns a text range. You can use the same methods and properties on this range as you do for ranges created using createTextRange. 

Creating a TextRange object on the body will not include the content inside a textArea or button. Conversely, you cannot change the start or end position of a text range over the textArea or button to move outside the scope of these particular elements. Use the properties provided on each element, isTextEdit and parentTextEdit, to walk the hierarchy. If the document above contained a textArea, a createTextRange on the body object would not find the position where the user actually clicked. The following reworks the above example to handle this case. 

Hide Example

HTMLHEAD
TITLEmoveToPoint Example/TITLE
script for=document event=onclick
     var r
     if(window.event.srcElement.isTextEdit)
           {
            r=window.event.srcElement.createTextRange();
     }else{
            var el=window.event.srcElement.parentTextEdit;
            r=el.createTextRange();
           }
     r.moveToPoint(window.event.x, window.event.y);
     r.expand("word");
     r.select();
/script
/HEAD
BODY

H1 id=myH1Click on a word and it will highlight/H1

TEXTAREA
There's text in this element too that you could click on
/TEXTAREA

/BODY/HTML
Show Me
Getting the Content of a TextRange
The content of a TextRange object can be viewed with the text or htmlText property on the TextRange object. The text property is a read/write property that is similar to the innerText properties on the element objects, only this replaces the text encompassed by a TextRange object. 

The htmlText property is a read-only property that lets you examine the HTML that is contained within the start and end points of the TextRange object. To add rich HTML content to the text range, use the pasteHTML method. Although you can paste any HTML text that you want into a text range, the pasteHTML method does not preserve the hierarchy of the document, as do the innerHTML and outerHTML properties. Although pasteHTML won't fail if you paste invalid or inappropriate tags into the range, the resulting document might not look or behave the way you expect. If you paste an HTML fragment, the fragment is automatically closed to prevent it from affecting subsequent text and elements. For example, this means that if your scripts rely on ordinal positions in the document's all collection, after a pasteHTML, the sourceIndex into the document.all collection might point to a different element. 

Comparing Ranges
You can create more than one text range at a time, using them for independent, simultaneous access to different portions of the text in an element. You can also copy a text range by using the duplicate method. This is useful if you want temporary access to a portion of the original range but don't want to bother re-creating or restoring the original range. You can determine the relationship of one text range to another by using methods such as isEqual and inRange. 

Because the object model never holds on to a text range, you'll need to re-create any range whenever control leaves and then reenters your code. For example, any text range objects created by an event handler are discarded when the event handler returns. 

You can determine whether one range is entirely contained within another text range by using the inRange method. You can determine whether two text ranges are identical by using the isEqual method. Text ranges are identical if they start and end at exactly the same positions. Note that identical text ranges are always considered to be within one another, meaning the inRange method returns true for these. 

You can set the start or end point of a range to match the start or end point of another range by using the setEndPoint method. The method takes two parameters: a string describing which end points to transfer, and a range from which the source end point is taken. The following example sets the end of the range r1 to the start of r2. 

r1.setEndPoint( "StartToEnd", r2 )
You can also use StartToStart, EndToStart, and EndToEnd to set the end points. 

You can compare the start or end points of two ranges by using the compareEndPoints method. This method compares the end points and returns -1, 0, or 1, indicating whether the end point of the first range is less than, equal to, or greater than that of the second. 

A bookmark is an easy way to save the current start and end positions of a text range and quickly restore these positions when you need them. You create a bookmark for a given range by using the getBookmark method, which returns an opaque string that uniquely identifies the bookmark. (Opaque means the string cannot be examined or modified.) You use the string with the moveToBookmark method to move the text range back to the same start and end positions as when the bookmark was created. 

Commands
You can use commands to apply formatting and to carry out special actions on the text of a text range. You execute a command by using the execCommand method. You supply a command identifier and provide any additional command parameters. For example, you can change text to bold by using the Bold command as in the following Microsoft JScript (compatible with ECMA 262 language specification) example: 

var rng = document.body.createTextRange();
rng.collapse();
rng.expand("sentence");
rng.execCommand("Bold");
Show Me
The above example makes bold all text up to the first period in the document. 

Not all commands are available at all times. You can determine whether a command is available for a given text range by using the queryCommandEnabled and queryCommandSupported methods. For a list of commands, see Command Identifiers. 

To determine whether a given command has already been applied to a text range, use the queryCommandState method to retrieve the state of the command. The state is true if the command has been applied. 

(本文来源于图老师网站,更多请访问https://www.tulaoshi.com/webkaifa/)

来源:https://www.tulaoshi.com/n/20160219/1599724.html

延伸阅读
标签: Web开发
上一篇文章介绍了处理大量JavaScript对象的好选择:JSON JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,它采用完全独立于语言的文本格式,可替换XML成为AJAX程序中的数据交换格式。 它有两种结构: 1. 名称/值对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),纪录(...
标签: ASP
AppendToLog AppendToLog 方法将字符串添加到 Web 服务器日志条目的末尾。可以在脚本的同一部分中多次调用该方法。每次调用该方法时,都会在当前条目中添加指定的字符串。 语法 Response.AppendToLog string 参数 string 要添加到日志文件中的文本。由于 IIS 日志中的字段由逗号分隔,所以该字符串中不能包含逗号 (,)。字符串最大...
标签: ASP
Redirect Redirect 方法使浏览器尝试连接到其他 URL。 语法 Response.Redirect URL 参数 URL 浏览器重定向到的统一资源定位符 (URL)。 注释 任何在页中显式设置的响应正文内容都将被忽略。然而,此方法不向客户端发送该页设置的其他 HTTP 标题。将产生一个将重定向 URL 作为链接包含的自动响应正文。 Redirect 方法发送下列显...
标签: ASP
ServerVariables ServerVariables 集合检索预定的环境变量。 语法 Request.ServerVariables ( server environment variable ) 参数 服务器环境变量 指定要检索的服务器环境变量名。可以使用下面列出的值。 变量 说明 ALL_HTTP客户端发送的所有 HTTP 标题文件。ALL_RAW检索未处理表格中所有的标题。ALL_RAW 和 ALL_HTTP 不...
标签: ASP
IsClientConnected IsClientConnected 属性只读,它指示自上次调用 Response.Write 之后,客户端是否与服务器相连。 语法 Response.IsClientConnected ( ) 注释 该属性允许用户在客户端与服务器没有连接的情况下有更多的控制。例如,在从客户端提出请求起到服务器作出响应,其间要用去很长一段时间的情况下,这就可能有助于确保在继...

经验教程

534

收藏

80

精华推荐

Asp Object 之:BinaryRead

Asp Object 之:BinaryRead

残留feng

Asp Object 之:Request

Asp Object 之:Request

泡泡and面面

Asp Object 之:Expires

Asp Object 之:Expires

洛神赋61

微博分享 QQ分享 QQ空间 手机页面 收藏网站 回到头部