Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Use JavaScript to read the selected text and copy it to the clipboard

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

Ask most developers how to copy the content selected by the user to the clipboard and they will mention the requirements of Flash (hence the popularity of scripts such as Zeroclipboard). However, the adjustment of this idea is now due to recent improvements in browser support for key technologies in JavaScript, which makes it possible to copy to the clipboard itself. This JavaScript method is supported in IE9 +, Firefox 41 + and Chrome 42 +, resulting in native cut / copy support for the browser itself. In this tutorial, we will see how to read the text selected by the user, dynamically select some text on the page, and last but not least, copy the selection to the clipboard, all using only JavaScript. We are now entering a Flash-free zone! Document.execCommand ()

Retrieve the text content selected by the user

Let's start at the top and retrieve the content selected by the user on the page to any text content. To do this, we used all the methods supported by modern browsers and IE9 +: window.getSelection ()

one

two

three

four

five

six

seven

Function getSelectionText () {

Var selectedText = ""

If (window.getSelection) {/ / all modern browsers and IE9 +

SelectedText = window.getSelection (). ToString ()

}

Return to selectedText

}

Window.getSelection () returns the currently selected text on the page and the object that contains the data. To retrieve the actual text, we use it to convert it to a string. The following example calls our function when the user hovers over the document to see what the user has selected, if any: SelectiontoString () getSelectionText ()

one

two

three

four

five

six

Document.addEventListener ('mouseup',function () {

Var thetext = getSelectionText ()

If (thetext.length > 0) {/ / check if some text is selected

Console.log (thetext) / / record any text content selected by the user on the page

}

}, false)

We first check to see if some text is selected, just as if the user just clicked on the page, no.

Select and read the text content of non-form elements on the page

Moving forward, we can also be responsible for dynamically selecting and then retrieving the content we want on the page, rather than simply retrieving the content selected by the user, such as the content of a particular DIV. This is very different from simply using the element innerHTML or innerText attribute to get its content; we want to actually select the content through JavaScript, which opens up other possible actions, such as copying it to the user's clipboard.

To select the text content of a non-form field element, we first create a new Range object and set it to contain the desired element. Then, add the range to the Selection object to actually select it. Let's see how it works, and this function dynamically selects the text content of the element based on the element passed in:

one

two

three

four

five

six

seven

Function selectElementText (el) {

Var range = document.createRange () / / create a new scope object

Range.selectNodeContents (el) / / sets the range to contain the required element text

Var selection = window.getSelection () / / get the Selection object from the text selected by the current user

Selection.removeAllRanges () / / deselect any text selected by the user (if any)

Selection.addRange (range) / / add a scope to the Selection object to select it

}

To create an object to add scope, we use it; because by default this method returns the text (if any) selected by the user, we immediately call its method to clear the tablet. Then we start to create a blank range, zero the contents of the element for selection, and then add the range to the object for selection. Selection window.getSelection () removeAllRanges () range.selectNodeContents () Selection

Once we have selected the text we want to read, we turn to our previous getSelectionText () method to read the contents of the selected element, such as:

Demo:

"my mother always said, 'Life is like a box of chocolates. You never know what you're gonna get.'" -Forrest

Select and retrieve text

Code:

one

two

three

four

Var para = document.getElementById ('para')

SelectElementText (para) / / Select the element text we want to read

Var paratext = getSelectionText () / / read user selection

Alert (paratext) / / remind "my mother always says..."

Select and read the contents of form elements, such as INPUT text or TEXTAREA

In order to select field values related to reading the table, such as INPUT text and TEXTAREA, this process is different from selecting regular text. Most of us already know the entire value of the selected form field, and we can use inputElement.select () * and retrieve that value to probe inputElement.value. However, you can also programmatically select a portion of the field value and get that value. Let's see how to do this.

-programmatically select a portion of the field value

To dynamically select INPUT text or part of a TEXTAREA element, use this field to indicate the starting and ending indexes you want to select: formElement.setSelectionRange ()

one

two

three

four

Var emailfield = document.getElementById ("email")

Emailfield.focus () / / this is required in most browsers before setSelectionRange () works

Emailfield.setSelectionRange (0d5) / / Select the first five characters of the input field

Emailfield.setSelectionRange (5 minutes emailfield. Value.length) / / Select the fifth to last character of the input field

Note that the second parameter, formElement.setSelectionRange (), should be the index of the end character to be selected plus 1, so to select the first five characters of the form field, the end index value to enter should be 5 or 4 (index of the fifth character) plus 1.

Demo:

Select the first five characters, select the fifth to the last character.

* Note: on iOS devices (starting with iOS9), using inputElement.select () to quickly select the contents of all form elements doesn't seem to work. However, using inputElement.setSelectionRange () is true. Therefore, select the text of all form fields across browsers and devices as follows:

InputElement.setSelectionRange (0, inputElement.value.length)

-read the selected portion of the field value

No matter how you select a portion of the value of a form field, whether by using setSelectionRange () to dynamically select that part, or by the user dragging his / her mouse to make a user-defined selection, the selection is retrieved by getting the start and end characters of the exponential selection and then using them to extract the part from the value of the form field. We can use the following methods to get the index selected by the activity:

FormElement.selectionStart: the index of the first character of the selected text. If no text is selected, it contains the index of the characters after the input cursor.

FormElement.selectionEnd: the index of the last character of the selected text. If no text is selected, it contains the index of the characters after the input cursor.

The above properties are particularly useful for getting any user-selected text from a form field, where the selected index is not yet known. The following demonstration responds to what the user selects from the TEXTAREA using the following properties:

Demo (select some text in textarea):

Output:

Code:

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

Here are some words.

Of

Var quotearea = document.getElementById ('quote')

Var output = document.getElementById ('output')

Quotearea.addEventListener ('mouseup',function () {

If (this.selectionStart! = this.selectionEnd) {/ / check whether the user has selected some text in the field

Var selectedtext = this.value.substring (this.selectionStart,this.selectionEnd)

Output [XSS _ clean] = selectedtext

}

}, false)

We mouseup attach an "" event to the target TEXTAREA to listen when the user puts it in it. Inside the event handler, to detect what the user has selected, first, we check to see if the TEXTAREA selectionStart and selectionEnd properties contain different values-if they are the same, nothing is selected, in which case they all point to the character behind the input cursor. If their values are different, we continue to map the index of the selected text to the value of the form field value to use the export of the actual selected text formElement.value.substring ().

Copy the selected text to the user clipboard

Well, now for the details of how to read the selection on the page, whether on the page or within a particular DIV or form element, we can move on to the next pressing problem, which is actually copying that content to the clipboard. As mentioned at the beginning of this tutorial, it boils down to using this method to execute a command to "copy" (or "cut") text to the clipboard: document.execCommand ()

one

two

three

four

five

six

seven

eight

nine

Function copySelectionText () {

Var copysuccess / / var checks whether the execCommand is executed successfully

Try {

Copysuccess = document.execCommand ("copy") / / run the command to copy the selected text to the clipboard

} catch (e) {

Copysuccess = false

}

Return to copysuccess

}

The key here is the line document.execCommand ("copy"), which actually performs an action to copy anything currently selected on the page to the clipboard. To check whether the browser execCommand () supports this method correctly, we put the operation in a try/catch () block; if the call to execCommand () fails, we know that the browser does not support this method.

We can use our new morph copySelectionText () function with any previous method to select / retrieve some text and copy it to the clipboard. For example, when a user hovers over a document, the following code snippet copies whatever the user selects on the page:

one

two

three

Document.body.addEventListener ('mouseup',function () {

Var copysuccess = copySelectionText () / / copy user-selected text to the clipboard

}, false)

We can improve this process, but if the user chooses to actually contain some data, only "copy" is performed; for example, if the user simply clicks on the page without highlighting anything, no data is selected, in which case, the replication operation should be aborted. This can be done by pre-viewing the content selected by the user:

one

two

three

four

five

six

Document.body.addEventListener ('mouseup',function () {

Var selected = getSelectionText () / / call getSelectionText () to view the selection

If (selected.length > 0) {/ / if the selected text length is greater than 0

Var copysuccess = copySelectionText () / / copy user-selected text to the clipboard

}

}, false)

Now it's time for a live demonstration. Try selecting any of the text in the following paragraphs to see its contents copied to the clipboard (then press "Ctrl V" to paste and confirm). I also added a temporary tooltip to indicate success each time:

Demo (select any text in the following paragraph to copy it to the clipboard):

"in order to enjoy health, bring real happiness to the family, and bring peace to all, one must first train and control his mind. If a man can control his mind, he can find the way to enlightenment, and all wisdom and virtues will naturally come to him." -Buddha

Code:

one

two

three

four

five

six

seven

eight

nine

Createtooltip () / / creates a tooltip by calling ONCE per page. Please refer to the comments below

Var buddhaquote = document.getElementById ('buddhaquote')

Buddhaquote.addEventListener ('mouseup',function (e) {

Var selected = getSelectionText () / / call getSelectionText () to view the selection

If (selected.length > 0) {/ / if the selected text length is greater than 0

Var copysuccess = copySelectionText () / / copy user-selected text to the clipboard

In showtooltip (e)

}

}, false)

Note: click here to get the source of the tooltip function.

Copies the selected form field values to the user clipboard

Go on, we can easily perform the same hat technique on the form field values. In the next example, we add a control next to the INPUT text field so that the user can quickly copy its value:

Demo:

Share the copy of this tutorial

Code:

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

Function copyfieldvalue (eMagneid) {

Var field = document.getElementById (id)

Field.focus ()

Field.setSelectionRange (0field. Value.length)

Var copysuccess = copySelectionText ()

If (copysuccess) {

In showtooltip (e)

}

}

Share this tutorial

Copy

Copy the contents of DIV to the clipboard

Finally, for better measurement, we can see an example that automatically selects and copies the contents of the DIV to the clipboard when you click it:

Demo (click any of the quotation marks below to select its contents):

"just when the caterpillar thought the world was coming to an end, he became a butterfly." -Proverbs

"Great minds discuss ideas; average thoughts discuss events; small thoughts discuss people." -Eleanor Roosevelt

"No one will make you feel inferior without your consent." -Eleanor Roosevelt

Code:

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

twenty

twenty-one

twenty-two

twenty-three

twenty-four

twenty-five

twenty-six

twenty-seven

twenty-eight

twenty-nine

thirty

thirty-one

"just when the caterpillar thought the world was coming to an end, he became a butterfly." -Proverbs

"Great minds discuss ideas; average thoughts discuss events; small thoughts discuss people." -Eleanor Roosevelt

"No one will make you feel inferior without your consent." -Eleanor Roosevelt

Var motivatebox = document.getElementById ('motivatebox')

Motivatebox.addEventListener ('mouseup',function (e) {

Var e = e | | event / / balancing event objects between modern and old IE browsers

Var target = e.target | | e.srcElement / / get the target element over the mouse

If (target.className = = 'motivate') {

SelectElementText (target) / / Select the element text we want to read

Var copysuccess = copySelectionText ()

If (copysuccess) {

In showtooltip (e)

}

}

}, false)

There's nothing new here-we're just monitoring the "" event of the mouseup quotation mark DIVs shared parent container to detect when the user clicks on one of the internal DIV. When this happens, we select the contents of the DIV and copy it to the clipboard using the function we created earlier.

The conclusion is that

As you can see, reading and, more importantly, copying text to the clipboard can now be entirely JavaScript events. As Flash is no longer popular with browsers and users, this is really good news. All of the above examples apply to IE9 +, Firefox 41 + and Chrome 42 +.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report