[英]How to copy newline characters from HTML div to textarea in jQuery?
[英]Copy content from div to textarea in HTML
主要目標:
創建一個網站,該網站將實時預覽HTML / CSS代碼。 鏈接
進一步來說 :
HTML / CSS代碼將在某些特定部分由用戶進行編輯。 因此,實時預覽中的代碼將不會源自文本區域,而是會源自div。
到目前為止的進展:所以,在我之前的問題中:
a) 問題1
b) 問題2
從黑匣子獲取代碼后,我試圖找到一種使實時預覽框正常工作的方法。 它不起作用,因為代碼是在div
標簽而不是textarea
。 我想補充一點, div
標簽中的代碼使用xmp
標簽,因為某些部分可以從用戶進行編輯。
因此,我發現最好的解決方案是保留div
標簽,以便用戶更改/更改代碼,然后使用隱藏的textarea
進行實時預覽。
主要問題:
如何在textarea
復制div的內容? 我正在使用JS腳本(如下)將其復制到剪貼板中。 是否可以在textarea
內容中復制它?
完成此操作后,我將嘗試使其在沒有復制(更新代碼)按鈕的情況下工作。 這是我的腳本:
$(document).ready(function() {
var highestBox = 0;
$('.top').each(function() {
if ($(this).height() > highestBox) {
highestBox = $(this).height();
}
});
$('.top').height(highestBox);
});
document.getElementById("copyButton1").addEventListener("click", function() {
copyToClipboard(document.getElementById("copyTarget1"));
});
document.getElementById("copyButton2").addEventListener("click", function() {
copyToClipboard(document.getElementById("copyTarget2"));
});
function copyToClipboard(elem) {
// create hidden text element, if it doesn't already exist
var targetId = "_hiddenCopyText_";
var isInput = elem.tagName === "INPUT" || elem.tagName === "textarea";
var origSelectionStart, origSelectionEnd;
if (isInput) {
// can just use the original source element for the selection and copy
target = elem;
origSelectionStart = elem.selectionStart;
origSelectionEnd = elem.selectionEnd;
} else {
// must use a temporary form element for the selection and copy
target = document.getElementById(targetId);
if (!target) {
var target = document.createElement("textarea");
target.style.position = "absolute";
target.style.left = "-9999px";
target.style.top = "0";
target.id = targetId;
document.body.appendChild(target);
}
target.textContent = elem.textContent;
}
// select the content
var currentFocus = document.activeElement;
target.focus();
target.setSelectionRange(0, target.value.length);
// copy the selection
var succeed;
try {
succeed = document.execCommand("copy");
} catch(e) {
succeed = false;
}
// restore original focus
if (currentFocus && typeof currentFocus.focus === "function") {
currentFocus.focus();
}
if (isInput) {
// restore prior selection
elem.setSelectionRange(origSelectionStart, origSelectionEnd);
} else {
// clear temporary content
target.textContent = "";
}
return succeed;
}
干杯
我結合了我在網上找到的許多東西,並使用以下腳本使其起作用:
var MyDiv1 = document.getElementById('copyTarget2');
var MyDiv2 = document.getElementById('copyTarget1');
$('#Update').click(function(e) {
textareahtml.value=$.trim(MyDiv1.innerText)
textareacss.value=$.trim(MyDiv2.innerText)
});
然后在HTML代碼中放置一個按鈕
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.