Home Web Front-end JS Tutorial Summary of how to use textRange object in JavaScript_javascript skills

Summary of how to use textRange object in JavaScript_javascript skills

May 16, 2016 pm 04:07 PM
javascript object

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 attributes and methods of TextRange:

Attributes

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 width of the rectangle bound to the TextRange object
text sets or gets the text contained in the range
Method

moveStart changes the starting position of the range
moveEnd changes the end position of the range
collapse moves the insertion point to the beginning or end of the current range
move Collapses the given text range and moves the empty range the given number of cells
execCommand executes a command on the current document, current selection, or given range
select sets the current selection area to the current object
findText searches for text within 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 point and end point

 3. Operate the range

Copy code The code is as follows:






Move the cursor to the position


1.createTextRange()

Create a TextRange object. Elements such as BODY, TEXT, TextArea, and BUTTON 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 specified are 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()

The select() method selects 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 coincide

Copy code The code is as follows:









The above 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 start point is the first character of the container and the end point is the last character

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

Copy code The code is as follows:
function selectText()
{
var rng = txtBox.createTextRange();
rng.moveStart("character",1);
rng.moveEnd("character",-1);
rng.select();
}

시작점을 한 문자 앞으로 이동시키고 끝점을 한 문자 뒤로 이동시키면 선택된 범위가 첫 번째 문자와 마지막 문자를 제외한 전체 텍스트 범위임을 알 수 있습니다.

5.collapse([부울])

collapse() 메서드를 사용하면 현재 크기부터 문자 사이의 단일 삽입 지점까지 텍스트 범위를 겹칠 수 있습니다. Collapse() 메서드의 선택적 매개 변수는 범위가 현재 범위의 시작 또는 끝에서 겹치는지 여부를 나타내는 부울 값입니다. 기본값은 true이며 시작점과 일치합니다.

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

TextRange 객체의 가장 유용한 메서드 중 하나는 findText() 메서드입니다. 이 메서드의 기본 동작은 시작 지점에서 끝 지점까지 텍스트 범위를 찾아 대소문자를 구분하지 않는 문자열 일치 항목을 검색하는 것입니다. 범위에서 인스턴스가 발견되면 범위의 시작점과 끝점이 이 텍스트에 배치되고, 메서드는 true를 반환하고, 그렇지 않으면 false를 반환하고 시작점과 끝점은 변경되지 않은 상태로 유지됩니다. 이 방법은 태그나 속성이 아닌 표시 텍스트만 검색합니다.

선택적 매개변수 searchScope는 시작점부터의 문자 수를 나타내는 정수 값입니다. 값이 클수록 검색 범위에 더 많은 텍스트가 포함됩니다. 음수 값을 사용하면 검색 작업이 시작점부터 뒤로 검색됩니다. 현재 출발점.

선택적 플래그 매개변수는 검색이 대소문자를 구분하는지, 아니면 전체 단어만 일치하는지를 설정하는 데 사용됩니다. 매개변수는 비트 수학을 사용하여 하나 이상의 설정을 보유할 수 있는 단일 값을 계산하는 정수 값입니다. 전체 단어를 일치시키는 값은 2이고, 대문자와 소문자를 일치시키는 값은 4입니다. 하나의 항목만 일치시키려면 원하는 값만 제공하면 충분하지만 두 동작 모두 비트 XOR 연산자를 사용합니다. (^ 연산자 )는 값을 6으로 만듭니다.

findText() 메서드의 가장 일반적인 적용에는 범위 내 찾기 및 바꾸기 작업과 문자열 인스턴스 서식 지정이 포함됩니다. 검색은 일반적으로 범위의 현재 시작점에서 시작되므로 시작점을 이동해야 합니다. 일치하는 텍스트(예: 예 3)의 끝으로 이동한 후 findText()는 계속해서 나머지 텍스트 범위를 탐색하여 다른 일치 항목을 찾을 수 있습니다. Collapse(false) 메소드를 사용하면 시작점이 첫 번째 일치 범위의 끝점으로 이동하도록 강제할 수 있습니다. 따라서 예제 3의 findText() 함수는 다음과 같이 수정될 수도 있습니다.

코드 복사 코드는 다음과 같습니다.

<스크립트 언어="javascript"> var rng = txtBox.createTextRange()
함수 findText(str)
{
​ if(str=="")
​ 복귀
​ if(rng.findText(str))
  {
​ rng.select()
 rng.collapse(false)
   }
//검색 후 마지막 범위를 찾을 수 없으면 검색이 완료되었다는 메시지를 표시하고 rng의 원래 범위를 복원합니다. (그렇지 않으면 새 검색을 수행할 수 없습니다.)
​ 그 외
  {  
​​ Alert("검색 완료")
​ rng = txtBox.createTextRange()
   }
} 


6.parentElement()

parentElement() 메서드는 텍스트 범위가 포함된 컨테이너에 대한 참조를 반환합니다.

커서가 선택한 텍스트의 DOM 객체를 가져옵니다

코드 복사 코드는 다음과 같습니다.
<스크립트> 함수 getParElem()
{
var rng = document.selection.createRange()
var 컨테이너 = rng.parentElement()
//alert(container.getAttribute("id")||container.getAttribute("value")||container.getAttribute("type"))
경고(컨테이너.태그이름)
}
스크립트>


Body에만 속하는 텍스트입니다
div
에 포함된 텍스트입니다.

p


에 포함된 텍스트입니다.
이것은 div->strong




Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1270
29
C# Tutorial
1249
24
WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to convert MySQL query result array to object? How to convert MySQL query result array to object? Apr 29, 2024 pm 01:09 PM

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

How do PHP functions return objects? How do PHP functions return objects? Apr 10, 2024 pm 03:18 PM

PHP functions can encapsulate data into a custom structure by returning an object using a return statement followed by an object instance. Syntax: functionget_object():object{}. This allows creating objects with custom properties and methods and processing data in the form of objects.

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

What should I pay attention to when a C++ function returns an object? What should I pay attention to when a C++ function returns an object? Apr 19, 2024 pm 12:15 PM

In C++, there are three points to note when a function returns an object: The life cycle of the object is managed by the caller to prevent memory leaks. Avoid dangling pointers and ensure the object remains valid after the function returns by dynamically allocating memory or returning the object itself. The compiler may optimize copy generation of the returned object to improve performance, but if the object is passed by value semantics, no copy generation is required.

Analyze the differences between heap and stack in Java and their application scenarios Analyze the differences between heap and stack in Java and their application scenarios Feb 24, 2024 pm 11:12 PM

The difference between Java heap and stack and application scenario analysis require specific code examples. In Java programs, heap and stack are two commonly used data structures, and they assume different roles and functions in memory. Understanding the difference between heap and stack is crucial to writing efficient Java programs. First, let's take a look at the Java heap. The heap is an area used to store objects. All objects created in the program are stored in the heap. The heap is where memory is dynamically allocated and released while the program is running. It is not subject to any restrictions and can be automatically allocated and released as needed.

See all articles