Touch copy function of mobile terminal

Posted by beginPHP on Sat, 07 Dec 2019 14:36:07 +0100

Before the company's project, a user needs to automatically copy a string code for him as soon as he enters the page and touches his mobile phone.. wtf? And that? Well, when the demand comes out, let's realize it...

When users come in and touch their mobile phones, they will generate three events: touchstart, touchmove and touchend. We can't directly write these three events to copy, which will affect their default events. What we have to do is to be aware of the ghosts...

So, inside the function, we need to use the following code

    // part1

    var t = document.createElement('textarea');  // Sir, make a text box

    t.id = "WpCopy";

    t.value="What needs to be copied";

    t.setAttribute('readOnly','readOnly');
    t.setAttribute('style',"font-size: 12pt; border: 0px; padding: 0px; margin: 0px; position: absolute; left: -9999px; top: 0px;");  //Let him disappear into the field of vision

    document.getElementsByTagName('body')[0].appendChild(t);  // Add to page

    var WpCopy = document.getElementById('WpCopy');  // Declaration displayed
    
    WpCopy.focus();  // Focus of acquisition

Here we create a hidden textbox that can be assigned. Next, we need to judge in the event and let the value in the textbox run to the user's pasteboard...

    // part1

    // Declare an event function
    function touch (event) {
        var event = event || window.event,
              link = ' ';
        switch(event.type){

            case "touchstart":

                link = event.target; //At the beginning of touch, assign the touch object to the previously declared variable and save it
                
                break;

            case "touchend":

                WpCopy.setSelectionRange(0, WpCopy.value.length); // At the end of touch, select all text boxes
                document.execCommand('copy', true); // And copy to the pasteboard
                if(link != '') { 
                    link.click();  // This step determines that if the user clicks the page element normally, continue to let him execute
                }

                break;

            case "touchmove":

                link = ""; // If the user moves the touch screen, leave the variable blank, and the original event of the touch start element will not be triggered

                break;
        }
    }

At this stage, you can basically complete the requirements. Next, integrate these two pieces of code into a function method to facilitate page calling

function loadCopy (){
    $(document).on('touchstart',touch);
    $(document).on('touchmove',touch);
    $(document).on('touchend',touch);

    // Put in part1, part2;
}

// Call loadCopy on the required page

Such a requirement is actually the application of execCommand replication... Bad code, hope to point out

Topics: Javascript Mobile