search
HomeWeb Front-endH5 TutorialMobile terminal implements selected and highlighted all-selected text events

This time I will bring you the event of selecting and highlighting all selected text on the mobile terminal. What are the precautions on implementing the event of selecting and highlighting all selected text on the mobile terminal. The following is a practical case, let's take a look.

Recently, we need to implement a copy function on the page for HTML5 WebAPP: when the user clicks and long-presses the text, all the text will be selected and the system "Copy" menu will pop up. The user can click "Copy" to perform the copy operation, and then paste it into Search the AppStore for the corresponding application. The reason why the link form is not used to jump directly to the corresponding AppStore application is to increase the weight of the promoted enterprise App through the user's active input of keyword searches. Therefore, this "copy" function is crucial to the user experience.

I tried some methods, but the compatibility on the Android/iOS platform is not very good. In the WeChat browser, it is easy to long-press text to activate the system menu and highlight all selected text content. But the performance in other browsers is not very consistent. Including simulating focus input, JavaScript Selection, and using the a tag to try to activate the system menu. These methods all have compatibility flaws.

1) Although using the a tag with href attribute and long pressing the text on uc browser and Baidu browser, the "free copy"/"select text" menu will appear. After selecting this menu, the "full text" will appear. "Select/Copy" menu, but in the system browsers of some Android phones and iPhones, it is regarded as a pure link, and only "Copy Link" pops up without the "Copy Text" menu. Moreover, even if only a small number of browsers are considered feasible, this will add one more step to the user's operation and increase complexity. So this solution is not advisable.

2) Using selection and range methods, you need to consider the compatibility of different browsers. The code is as follows:

function selectText(element) {  
  var doc = document,  
      text = docgetElementById(element),  
      range,  
      selection;  
  
  if (docbodycreateTextRange) {  
      range = documentbodycreateTextRange();  
      rangemoveToElementText(text);  
      rangeselect();  
  } else if (windowgetSelection) {  
      selection = windowgetSelection();          
      range = documentcreateRange();  
      rangeselectNodeContents(text);  
      selectionremoveAllRanges();  
      selectionaddRange(range);  
      /*if(selectionsetBaseAndExtent){ 
          selectionsetBaseAndExtent(text, 0, text, 1); 
      }*/  
  }else{  
      alert("none");  
  }  
}

Unfortunately, it is still not possible to highlight by clicking or long pressing on iPhone Safari Select all text (since window.getSelection is also supported, why can’t the text be selected by default after the addRange operation in Safari browser? If you know the reason, please leave a message). Therefore, this approach is flawed. The method of actively selecting a text area is attached later.

3) iPhone users may know that if you long press the blank area around the text in a text selection, Safari will automatically highlight and select all the text in the selection (the target text needs to be placed in an independent p block-level container ). According to this feature, use CSS margin to modify it. Using this feature, you can solve the incompatibility of the second method above on iOS devices. After testing, regardless of the Android and iOS platforms, the system browsers that come with general mobile phones are compatible. As for mobile products from other manufacturers such as UC Browser and Baidu Browser, due to different mechanisms, you can only use the "free copy" function provided by these browser menus.

So, I combined the second and third methods and used the taphold event in jQuery mobile to simulate the longtap operation to trigger the copy menu of the mobile system. This can basically be done on all mobile device browsers. You can long press the text area to highlight all text content. One more thing, taphold's compatibility bugs are not detailed here with solutions. If your project requires excellence, you can search for solutions yourself.

My solution is listed below. The specific code is as follows:

HTML code:

<p>  
    </p><p>  
        1、必须首次下载才生效<br>  
        2、不能从排行榜下载哦  
    </p>  
    <p>  
        </p><p><span>三国艳义手机优化大师</span></p>                   
      
    <p>  
        <span><b>★</b>长按虚线框,拷贝关键词</span>  
    </p>  
    <a>去AppStore搜索下载</a>  

JavaScript code:

 <script>  
  
$("#kwd")bind("taphold", function(){ //不支持iPhone/iTouch/iPad Safari  
    var doc = document,   
        text = docgetElementById("kwd"),  
        range,   
        selection;  
    if (docbodycreateTextRange) {  
        range = documentbodycreateTextRange();  
        rangemoveToElementText(text);  
        rangeselect();  
    } else if (windowgetSelection) {  
        selection = windowgetSelection();          
        range = documentcreateRange();  
        rangeselectNodeContents(text);  
        selectionremoveAllRanges();  
        selectionaddRange(range);   
    }else{  
        alert("浏览器不支持长按复制功能");  
    }         
});  
  
</script>

Key CSS code:

cparea{  
    text-align: center;  
    font-family: Microsoft Yahei;  
    margin: -2em 0 0;  
}  
kwd{  
    display: inline-block;  
    color: #272727;  
    background-color: #fff;  
    font-size: 1875em;  
    font-size: 1875em;  
    padding: 75em 1em;  
    border: 1px dashed #e60012;  
    -webkit-user-select:element;   
    margin: 2em;  
}  
kwd span{  
    display: block;   
    border: 1px solid #fff;  
}  
kdes{  
    display: inline-block;  
    color: #212121;  
    font-size: 875em;  
    padding-top: 0;  
}  
kdes b{  
    color: #ed5353;  
    font-size: 25em;  
    padding-right: 1em;  
}

Description: The margin here: 2em is correct In order to realize the long-press selection all function on Safari browser, in order to respect the effect of restoring the design draft, the parent container .cparea uses negative margins to offset the 2em margin. In the end, not only was it visually consistent with the design drawing, but it also enabled long-pressing to select all to activate the system menu.

Finally, let me add the complete method to support Safari:

$("#kwd").bind("taphold", function(){  
    var doc = document,   
        text = docgetElementById("kwd"),  
        range,   
        selection;  
    if (docbodycreateTextRange) { //IE  
        range = documentbodycreateTextRange();  
        rangemoveToElementText(text);  
        rangeselect();  
  
    } else if (windowgetSelection) {   //FF CH SF  
        selection = windowgetSelection();          
        range = documentcreateRange();  
        rangeselectNodeContents(text);  
        selectionremoveAllRanges();  
        selectionaddRange(range);  
  
        //测试  
        consolelog(texttextContent);  
        textinnerText && consolelog(textinnerText);  //FireFox不支持innerText  
        consolelog(texttextContentlength);  
        textinnerText && consolelog(textinnerTextlength);   //在Chrome下长度比IE/FF下多1  
        consolelog(textfirstChildtextContentlength);  
        textinnerText && consolelog(textfirstChildinnerTextlength);  
        consolelog(textfirstChildinnerHTMLlength);  
  
        //注意IE9-不支持textContent  
        makeSelection(0, textfirstChildtextContentlength, 0, textfirstChild);  
        /* 
        if(selectionsetBaseAndExtent){ 
            selectionselectAllChildren(text); 
            selectionsetBaseAndExtent(text, 0, text, 4); 
        } 
        */  
    }else{  
        alert("浏览器不支持长按复制功能");  
    }  
  
});  
function makeSelection(start, end, child, parent) {  
    var range = documentcreateRange();  
    //consolelog(parentchildNodes[child]);  
    rangesetStart(parentchildNodes[child], start);  
    rangesetEnd(parentchildNodes[child], end);  
  
    var sel = windowgetSelection();  
    selremoveAllRanges();  
    seladdRange(range);   
}

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the use of date-related functions in JS

Detailed explanation of the use of foldable panels in JS

The above is the detailed content of Mobile terminal implements selected and highlighted all-selected text events. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Mastering Microdata: A Step-by-Step Guide for HTML5Mastering Microdata: A Step-by-Step Guide for HTML5May 14, 2025 am 12:07 AM

MicrodatainHTML5enhancesSEOanduserexperiencebyprovidingstructureddatatosearchengines.1)Useitemscope,itemtype,anditempropattributestomarkupcontentlikeproductsorevents.2)TestmicrodatawithtoolslikeGoogle'sStructuredDataTestingTool.3)ConsiderusingJSON-LD

What's New in HTML5 Forms? Exploring the New Input TypesWhat's New in HTML5 Forms? Exploring the New Input TypesMay 13, 2025 pm 03:45 PM

HTML5introducesnewinputtypesthatenhanceuserexperience,simplifydevelopment,andimproveaccessibility.1)automaticallyvalidatesemailformat.2)optimizesformobilewithanumerickeypad.3)andsimplifydateandtimeinputs,reducingtheneedforcustomsolutions.

Understanding H5: The Meaning and SignificanceUnderstanding H5: The Meaning and SignificanceMay 11, 2025 am 12:19 AM

H5 is HTML5, the fifth version of HTML. HTML5 improves the expressiveness and interactivity of web pages, introduces new features such as semantic tags, multimedia support, offline storage and Canvas drawing, and promotes the development of Web technology.

H5: Accessibility and Web Standards ComplianceH5: Accessibility and Web Standards ComplianceMay 10, 2025 am 12:21 AM

Accessibility and compliance with network standards are essential to the website. 1) Accessibility ensures that all users have equal access to the website, 2) Network standards follow to improve accessibility and consistency of the website, 3) Accessibility requires the use of semantic HTML, keyboard navigation, color contrast and alternative text, 4) Following these principles is not only a moral and legal requirement, but also amplifying user base.

What is the H5 tag in HTML?What is the H5 tag in HTML?May 09, 2025 am 12:11 AM

The H5 tag in HTML is a fifth-level title that is used to tag smaller titles or sub-titles. 1) The H5 tag helps refine content hierarchy and improve readability and SEO. 2) Combined with CSS, you can customize the style to enhance the visual effect. 3) Use H5 tags reasonably to avoid abuse and ensure the logical content structure.

H5 Code: A Beginner's Guide to Web StructureH5 Code: A Beginner's Guide to Web StructureMay 08, 2025 am 12:15 AM

The methods of building a website in HTML5 include: 1. Use semantic tags to define the web page structure, such as, , etc.; 2. Embed multimedia content, use and tags; 3. Apply advanced functions such as form verification and local storage. Through these steps, you can create a modern web page with clear structure and rich features.

H5 Code Structure: Organizing Content for ReadabilityH5 Code Structure: Organizing Content for ReadabilityMay 07, 2025 am 12:06 AM

A reasonable H5 code structure allows the page to stand out among a lot of content. 1) Use semantic labels such as, etc. to organize content to make the structure clear. 2) Control the rendering effect of pages on different devices through CSS layout such as Flexbox or Grid. 3) Implement responsive design to ensure that the page adapts to different screen sizes.

H5 vs. Older HTML Versions: A ComparisonH5 vs. Older HTML Versions: A ComparisonMay 06, 2025 am 12:09 AM

The main differences between HTML5 (H5) and older versions of HTML include: 1) H5 introduces semantic tags, 2) supports multimedia content, and 3) provides offline storage functions. H5 enhances the functionality and expressiveness of web pages through new tags and APIs, such as and tags, improving user experience and SEO effects, but need to pay attention to compatibility issues.

See all articles

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

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools