js文字选中及复制

文本输入框中文字选中及复制:

function selectText(element) {
    element.select();
     try {
        document.execCommand('copy');
    } catch (err) {
        console.log('该浏览器不支持点击复制到剪贴板');
    }
}

非文本输入框文字选中方法(仅选中没有复制):

function selectText(element) {
    if (document.body.createTextRange) {
        let range = document.body.createTextRange();
        range.moveToElementText(element);
        range.select();
    } else if (window.getSelection) {
        let selection = window.getSelection();
        let range = document.createRange();
        range.selectNodeContents(element);
        selection.removeAllRanges();
        selection.addRange(range);
    } else {
        alert('none');
    }
}

复制指定内容到剪切板:

function copyToClipboard(text) {
    let textArea = document.createElement('textarea');
    textArea.style.position = 'fixed';
    textArea.style.zIndex = -1;
    textArea.style.top = '0';
    textArea.style.left = '0';
    textArea.style.width = '1em';
    textArea.style.height = '1em';
    textArea.style.padding = '0';
    textArea.style.border = 'none';
    textArea.style.outline = 'none';
    textArea.style.boxShadow = 'none';
    textArea.style.background = 'transparent';
    textArea.value = text;
    document.body.appendChild(textArea);
    textArea.select();

    try {
        document.execCommand('copy');
    } catch (err) {
        console.log('该浏览器不支持点击复制到剪贴板');
    }

    document.body.removeChild(textArea);
}

你可能感兴趣的:(js,文字选中复制)