How to obtain the selected text using javascript code _ javascript tips-js tutorial

Source: Internet
Author: User
This article describes how to use javascript to obtain the selected text. For more information, see The Code is as follows:





New document




<BR> the fish in the river died unexpectedly, and the downstream residents were frequently infected with strange diseases. The plants along the river were continuously mutating. Is it a pesticide residue? Or biological attacks? Please pay attention to CCTV-10 "scientific exploration" tonight, the upcoming special program: "mysterious Riverside foot washing people-Chinese men's feet" <BR>

Obtain selected values


Script
String. prototype. trim = function (){
Return this. replace (/^ \ s + | \ s + $/g ,"");
}
/* Method 1 FF has a problem */
Function getSelectText (){
Try {
// IE: document. selection. createRange () W3C: window. getSelection ()
Var selectText = (document. selection & document. selection. createRange )? Document. selection. createRange (). text: window. getSelection (). toString ();
If (selectText! = Null & selectText. trim ()! = ""){
Return selectText;
}
} Catch (err ){}
}
/* Method 2 */
Function getSelectText2 (id ){
Var t = document. getElementById (id );
If (window. getSelection ){
If (t. selectionStart! = Undefined & t. selectionEnd! = Undefined ){
Return t. value. substring (t. selectionStart, t. selectionEnd );
} Else {
Return "";
}
} Else {
Return document. selection. createRange (). text;
}
}
Document. getElementById ('btn '). onclick = function (){
Document. getElementById ('show'). innerHTML = getSelectText2 ('content ');
}
Script

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.