![](/img/trans.png)
[英]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.