搜尋
首頁web前端js教程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: 



Welcome


Overview


Be sure to Refresh this page.




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


moveToPoint Example
<script> <BR> function selectMe() { <BR> var r=document.body.createTextRange(); <BR> r.moveToPoint(window.event.x, window.event.y); <BR> r.expand("word"); <BR> r.select(); <BR> } <BR></script>



Click on a word and it will highlight




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


moveToPoint Example
<script> <BR> var r <BR> if(window.event.srcElement.isTextEdit) <BR> { <BR> r=window.event.srcElement.createTextRange(); <BR> }else{ <BR> var el=window.event.srcElement.parentTextEdit; <BR> r=el.createTextRange(); <BR> } <BR> r.moveToPoint(window.event.x, window.event.y); <BR> r.expand("word"); <BR> r.select(); <BR></script>



Click on a word and it will highlight






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. 

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
2 个月不见,人形机器人 Walker S 会叠衣服了2 个月不见,人形机器人 Walker S 会叠衣服了Apr 03, 2024 am 08:01 AM

机器之能报道编辑:吴昕国内版的人形机器人+大模型组队,首次完成叠衣服这类复杂柔性材料的操作任务。随着融合了OpenAI多模态大模型的Figure01揭开神秘面纱,国内同行的相关进展一直备受关注。就在昨天,国内"人形机器人第一股"优必选发布了人形机器人WalkerS深入融合百度文心大模型后的首个Demo,展示了一些有趣的新功能。现在,得到百度文心大模型能力加持的WalkerS是这个样子的。和Figure01一样,WalkerS没有走动,而是站在桌子后面完成一系列任务。它可以听从人类的命令,折叠衣物

java Object转byte与byte转Object的方法是什么java Object转byte与byte转Object的方法是什么Apr 20, 2023 am 11:37 AM

Object转byte与byte转Object今天实现一下如何从Object去转为byte和如何从byte转为Object。首先,定义一个类student:packagecom.byteToObject;importjava.io.Serializable;publicclassstudentimplementsSerializable{privateintsid;privateStringname;publicintgetSid(){returnsid;}publicvoidsetSid(in

Java Object类中的方法怎么用Java Object类中的方法怎么用Apr 18, 2023 pm 06:13 PM

1.Object类介绍Object是Java默认提供的一个类。Java里面除了Object类,所有的类都是存在继承关系的。默认会继承Object父类。即所有类的对象都可以使用Object的引用进行接收。范例:使用Object接收所有类的对象classPerson{}classStudent{}publicclassTest{publicstaticvoidmain(String[]args){function(newPerson());function(newStudent());}public

PHP Notice: Trying to get property of non-object解决方法PHP Notice: Trying to get property of non-object解决方法Jun 24, 2023 pm 09:34 PM

PHPNotice:Tryingtogetpropertyofnon-object解决方法当你在使用PHP进行开发时,你可能会遇到这样的错误提示:“Notice:Tryingtogetpropertyofnon-object。”这个错误提示通常是由于你使用了一个未初始化的对象,或是你的对象在某一段代码中丢失了引用,从而无法正确访问属

THE是什么币种,THE币值得投资吗?THE是什么币种,THE币值得投资吗?Feb 21, 2024 pm 03:49 PM

THE是什么币种?THE(TokenizedHealthcareEcosystem)是一种数字货币,利用区块链技术,专注于医疗健康行业的创新和改革。THE币的使命是利用区块链技术提高医疗行业的效率和透明度,推动各方之间更高效的合作,包括患者、医护人员、制药公司和医疗机构。THE币的价值和特点首先,THE币作为一种数字货币,具备了区块链的优势——去中心化、安全性高、交易透明等,让参与者能够信任和依赖这个系统。其次,THE币的独特之处在于它专注于医疗健康行业,借助区块链技术改造了传统医疗体系,提升了

PHP Notice: Trying to get property of non-object的解决方法PHP Notice: Trying to get property of non-object的解决方法Jun 22, 2023 pm 02:43 PM

PHPNotice:Tryingtogetpropertyofnon-object的解决方法在使用PHP编写代码的过程中,我们可能会遇到“Tryingtogetpropertyofnon-object”的错误提示。这个错误提示通常是由于我们在尝试访问一个不存在的对象属性,导致代码出现了错误。这个错误提示通常会出现在以下情况下:对象不存

Java使用Object类的getClass()函数获取对象的运行时类Java使用Object类的getClass()函数获取对象的运行时类Jul 24, 2023 am 11:37 AM

Java使用Object类的getClass()函数获取对象的运行时类在Java中,每个对象都有一个类,这个类定义了对象的属性和方法。我们可以使用getClass()函数来获取对象的运行时类。getClass()函数是Object类的成员函数,因此所有的Java对象都可以调用该函数。本文将介绍getClass()函数的使用方法以及给出一些代码示例。使用get

Java Object类怎么使用Java Object类怎么使用May 13, 2023 pm 05:13 PM

1.equals方法==运算符比较运算符,即可以判断基本类型又可以判断引用类型如果判断基本类型,则判断值是否相等如果判断引用类型,则判断地址是否相等,即判断是否为同一个对象equals是object类的一个方法,只能判断引用类型object-equals源码:publicbooleanequals(Objectobj){return(this==obj);}可以清晰的看到,object类里的equals方法是判断对象的地址是否相同(是不是同一个对象)但是,其他数据类型类会重写equals方法,比

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前By尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。