Copying clipboard s on the mobile side and processing for iOS

Posted by berrberr on Mon, 02 Dec 2019 17:09:10 +0100

If there is such a demand: click a button, copy the text of a certain text to the clipboard for use, we need to use some methods.
On the pc, we can copy text using

document.execCommand('copy');

But not on the mobile side. The project I chose is clipboard, and the actual measurement effect is perfect.

On the official website of clipboard https://clipboardjs.com On, there are detailed installation and use methods:
We can use npm package or cdn. Address: https://github.com/zenorocha/...

I take cnd as an example:

<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js"></script>
<script>
    const clipboard = new ClipboardJS('.copy_click');
    $('.copy_click').addEventListener('touchstart', function() {
        let clipboard = new Clipboard('.copy_click');
        clipboard.on('success', function(e) {
            alert('Replication success')
        });
        clipboard.on('error', function(e) {
            alert('copy failed')
        });
    })
    function $(param){
        return document.querySelector(param)
    }
</script>
<body>
    <textarea class="summary_context" id="summary_context">12345</textarea>
    <div class="copy_click" data-clipboard-action="copy" data-clipboard-target="#Summary_context "onclick =" "> copy < / div >
</body>
<style>
    .summary_context{
        border:0;
        outline: none !important;
    }
</style>

Here are a few changes for iOS that can't be copied: if Android < textarea > can be replaced with < text > completely, it can save most of the style troubles, but textarea must be used on iOS. When using textarea, we should also consider a problem: highly adaptive problem. Textarea only displays two rows of text by default. If there are many texts to be copied, there are many rows in textarea, which need to be processed. I made a very clumsy way myself:

//Adapt to the height of textarea according to the number of words
function switchTextHeight(){
    let $summaryContext = $('#summary_context')
    let baseLen = 14; //One line can display 14 Chinese characters. If there are English letters, they can't be written so simply
    textLength = $summaryContext.value.length;
    for (let i=0; i<10; i++) { //Display up to 10 lines
        if (textLength >= baseLen * i && textLength <= baseLen * (i + 1)) {
            $summaryContext.style.height = 0.64 * (i + 1) + 'rem'; //0.64rem is the line height of a line of words. If there is automatic compilation, write px directly
        }
    }
}
function $(param){
    return document.querySelector(param)
}

Topics: Javascript iOS Mobile npm github