Skip to content

Instantly share code, notes, and snippets.

@comeontom
Created July 5, 2017 00:52

Revisions

  1. comeontom created this gist Jul 5, 2017.
    56 changes: 56 additions & 0 deletions jquery
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,56 @@
    function select(element) {
    var selectedText;
    var isReadOnly = element.hasAttribute('readonly');
    if (!isReadOnly) {
    element.setAttribute('readonly', '');
    }
    element.select();
    element.setSelectionRange(0, element.value.length);
    if (!isReadOnly) {
    element.removeAttribute('readonly');
    }
    selectedText = element.value;
    return selectedText;
    }

    function copyText(text) {
    var isRTL = document.documentElement.getAttribute('dir') == 'rtl';
    var fakeElem = document.createElement('textarea');
    // Prevent zooming on iOS
    fakeElem.style.fontSize = '12pt';
    // Reset box model
    fakeElem.style.border = '0';
    fakeElem.style.padding = '0';
    fakeElem.style.margin = '0';
    // Move element out of screen horizontally
    fakeElem.style.position = 'absolute';
    fakeElem.style[isRTL ? 'right' : 'left'] = '-9999px';
    // Move element to the same position vertically
    var yPosition = window.pageYOffset || document.documentElement.scrollTop;
    fakeElem.style.top = yPosition + 'px';
    fakeElem.setAttribute('readonly', '');
    fakeElem.value = text;
    document.body.appendChild(fakeElem);
    select(fakeElem);

    var succeeded;
    try {
    succeeded = document.execCommand('copy');
    }
    catch (err) {
    succeeded = false;
    }

    if (succeeded) {
    alert("复制成功");
    } else {
    alert("复制失败")
    }
    }

    $(document).ready(function () {
    $("div").click(function () {
    copyText("click copy");
    })

    });