js实现选中div内容并复制到剪切板

时间:2024-08-22 22:02:56
function copyUrl  () {

        var div = document.getElementById('xxxx');
if (document.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(div);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(div);
selection.removeAllRanges();
selection.addRange(range);
/*if(selection.setBaseAndExtent){
selection.setBaseAndExtent(text, 0, text, 1);
}*/
} else {
console.warn("none");
}
document.execCommand("Copy"); // 执行浏览器复制命令 alert("已复制好,可贴粘。");
}

参见:https://blog.****.net/boyit0/article/details/41082941