Using the TextRange Object

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>
<H1>Welcome</H1>
<CENTER><H2>Overview<H2></CENTER>
<P>Be sure to <B>Refresh</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

<HTML><HEAD>
<TITLE>moveToPoint 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

<HTML><HEAD>
<TITLE>moveToPoint 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=myH1>Click 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.

(0)

相关推荐

  • createTextRange()的使用示例含文本框选中部分文字内容

    复制代码 代码如下: <script language="javascript"> function test() { var rng=document.body.createTextRange(); alert(rng.text) } function test1() { var rng=document.body.createTextRange(); alert(rng.htmlText) } </script> <input type="b

  • 使用TextRange获取输入框中光标的位置的代码

    TextRange是用来表现HTML元素中文字的对象,虽然我们平时不太常用这个对象,可是它却在IE4.0中就已提供了.不过TextRange提供的调用方法却都比较晦涩,那么我们能拿它做些什么呢? TextRange的传统用途是对用户在Web页上用鼠标圈选的文字内容的操作,比如变化.删除.新增等.但其经典的用途却是,在Web页面中查找文字(这个比较简单)和获取输入框光标的位置.其中后者又有可以衍生出很多更有用的用途,比如:限制输入的MaskTextBox,其核心技术点就是获取输入框的光标位置,然后

  • 光标定位等TextRange的操作的范例代码

    光标位置 INPUT{border: 1 solid #000000} BODY,TABLE{font-size: 10pt} 点击 TextArea 实现光标定位 我怕来不及我要抱着你,直到感觉你的绉纹有了岁月的痕迹,直到视线变得模糊直到不能呼吸 为了你我愿意 动也不能动也要看着你,直到感觉你的发线有了白雪的痕迹,直到肯定你是真的直到失去力气让我们形影不离 如果全世界我也可以放弃,至少还有你值得我去珍惜而你在这里就是生命的奇迹 也许全世界我也可以忘记,就是不愿意失去你的消息你掌心的痣我总记得在

  • 使用TextRange获取输入框中光标的位

    TextRange是用来表现HTML元素中文字的对象,虽然我们平时不太常用这个对象,可是它却在IE4.0中就已提供了.不过TextRange提供的调用方法却都比较晦涩,那么我们能拿它做些什么呢? TextRange的传统用途是对用户在Web页上用鼠标圈选的文字内容的操作,比如变化.删除.新增等.但其经典的用途却是,在Web页面中查找文字(这个比较简单)和获取输入框光标的位置.其中后者又有可以衍生出很多更有用的用途,比如:限制输入的MaskTextBox,其核心技术点就是获取输入框的光标位置,然后

  • 教学演示-UBB,剪贴板,textRange及其他

    这是一个给新手学习代码的帖子,包含以下内容: 如何使用UBB代码,如何用js与剪贴板交互,如何使用textRange对象,如何使用自定义的快捷键操作,如何自动随窗口大小调整页面内容尺寸,正则表达式的使用等等 请仔细阅读代码,有问题请提问,目前代码开发完成度80%,IE only Blue Idea UBB Code Edit * { margin:0px; padding:0px; } html, body { background-color:buttonface; width:100%; h

  • js createRange与createTextRange的一些用法实例

    一.返回createTextRange的text和htmlText [Ctrl+A 全选 注:如需引入外部Js需刷新才能执行] 二.获取指定文本框中的选中的文字:只响应第一个文本框 [Ctrl+A 全选 注:如需引入外部Js需刷新才能执行] 三.页面文本倒序查找 abababababababa [Ctrl+A 全选 注:如需引入外部Js需刷新才能执行] 四.聚焦控件后把光标放到最后 [Ctrl+A 全选 注:如需引入外部Js需刷新才能执行] 五.得到文本框内光标位置 [Ctrl+A 全选 注:如

  • JavaScript中textRange对象使用方法小结

    TextRange对象是动态HTML(DHTML)的高级特性,使用它可以实现很多和文本有关的任务,例如搜索和选择文本.文本范围让您可以选择性的将字符.单词和句子从文档中挑选出来.TextRange对象是在HTML文档将要显示的文本流上建立开始和结束位置的抽象对象. 下面是TextRange的常用属性与方法: 属性 boundingHeight 获取绑定TextRange对象的矩形的高度 boundingLeft 获取绑定TextRange 对象的矩形左边缘和包含TextRange对象的左侧之间的

  • 处理文本部分内容的TextRange对象应用实例

    因用户要求方与TextRange对象结缘,用于处理JavaScript对象文本部分内容的一个对象. TextRange是用来表现HTML元素中文字的对象,虽然我们平时不太常用这个对象,可是它却在IE4.0中就已提供了.不过TextRange提供的调用方法却都比较晦涩,那么我们能拿它做些什么呢? TextRange的传统用途是对用户在Web页上用鼠标圈选的文字内容的操作,比如变化.删除.新增等.但其经典的用途却是,在Web页面中查找文字(这个比较简单)和获取输入框光标的位置.其中后者又有可以衍生出

  • Using the TextRange Object

    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 obje

  • 网页播放器Object使用详解

    一.代码 复制代码 代码如下: <object ID="javademo" CLASSID="clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA" HEIGHT="280" WIDTH="200"> <param name="AUTOSTART" value="0"> <param name="SHUFFLE&qu

  • Prototype Object对象 学习

    Object is used by Prototype as a namespace; that is, it just keeps a few new methods together, which are intended for namespaced access (i.e. starting with "Object."). 上面说的namespace个人理解就相当于C#中的静态类,提供工具函数的意思,和C#中的namespace应该不是一个概念.因为C#中的命名空间后面不会直

  • Javascript Object.extend

    既然是类,那么就有抽象类,具体类,类的继承,同时,类的成员可以有实例成员和静态成员.下面来看一下prototype是怎么做到这些的. 先看prototype中的以下的代码: 复制代码 代码如下: var Abstract = new Object(); Object.extend = function(destination, source) { for (property in source) { destination[property] = source[property]; } retu

  • Angular中使用$watch监听object属性值的变化(详解)

    Angular中的$watch可以监听属性值的变化,然后并做出相应处理. 常见用法: $scope.$watch("person", function(n, o){ //todo something... }) 但是对于一个对象中的某个属性值变化时,$watch似乎不管用了. 示例代码: <body> <div ng-controller="mainCtrl"> <input id="myText" type=&qu

  • Java源码解析之object类

    在源码的阅读过程中,可以了解别人实现某个功能的涉及思路,看看他们是怎么想,怎么做的.接下来,我们看看这篇Java源码解析之object的详细内容. Java基类Object java.lang.Object,Java所有类的父类,在你编写一个类的时候,若无指定父类(没有显式extends一个父类)编译器(一般编译器完成该步骤)会默认的添加Object为该类的父类(可以将该类反编译看其字节码,不过貌似Java7自带的反编译javap现在看不到了). 再说的详细点:假如类A,没有显式继承其他类,编译

  • 提示Trying to clone an uncloneable object of class Imagic的解决

    使用网上流传的一个程序实现pdf截图为png,需要使用Imagic扩展.在windows下安装完后提示: Fatal error: Trying to clone an uncloneable object of class Imagick in C:\www\hx\pdf_to_png.php on line 17 使用IIS和Apache均会有这个提示.经多次测试后,发现两种解决方法: 1.php.ini中; Enable compatibility mode with Zend Engin

  • PHP中把stdClass Object转array的几个方法

    方法一: 复制代码 代码如下: //PHP stdClass Object转array  function object_array($array) {      if(is_object($array)) {          $array = (array)$array;       } if(is_array($array)) {           foreach($array as $key=>$value) {               $array[$key] = object_

  • 浅谈Scala的Class、Object和Apply()方法

    Scala中如果一个Class和一个Object同名,则称Class是Object的伴生类.Scala没有Java的Static修饰符,Object下的成员和方法都是静态的,类似于Java里面加了Static修饰符的成员和方法.Class和Object都可以定义自己的Apply()方法,类名()调用Object下的Apply()方法,变量名()调用Class下的Apply()方法. class ApplyTest{ def apply() { println("This is a class,

随机推荐