Giả sử tất cả các phong cách của bạn là nội tuyến, bạn cần phải nhận được html của phần tử chứ không phải là văn bản. Một cái gì đó như:
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).html()).select(); //Note the use of html() rather than text()
document.execCommand("copy");
$temp.remove();
}
Chỉnh sửa dựa trên nhận xét:
Để sao chép định dạng cho một cái gì đó giống như một nội dung thư Gmail hoặc một tài liệu Word, bạn phải thực sự chọn phần tử như một loạt. Khi bạn chèn nội dung html vào một vùng văn bản, bạn thực sự đang sao chép văn bản thô. Bạn muốn làm một cái gì đó như thế này:
function copyToClipboard(element) { //Note, element should be a node rather than a jQuery instance.
var selection = window.getSelection(), //Get the window selection
selectData = document.createRange(); //Create a range
selection.removeAllRanges(); //Clear any currently selected text.
selectData.selectNodeContents(element); //Add the desired element to the range you want to select.
selection.addRange(selectData); //Highlight the element (this is the same as dragging your cursor over an element)
var copyResult = document.execCommand("copy"); //Execute the copy.
if(copyResult) //was the copy successful?
selection.removeAllRanges(); //Clear the highlight.
else
alert("Your browser does not support clipboard commands, press ctrl+c");
}
Tôi nghĩ rằng nó sẽ giúp ích nếu bạn mô tả nơi nó sẽ được dán. Nếu bạn lấy tất cả các html nó có thể không dán như bạn muốn nó. – Brian
Để nhắn tin gmail. Tôi chỉ muốn sao chép "nhấp để sao chép" giống như khi tôi chọn văn bản bằng chuột và sao chép văn bản đó. – FabianCannes
Tôi có thể thấy điều đó sẽ hữu ích như thế nào. Câu hỏi hay. +1. – Brian