将Div内容复制到文本区域或具有相同字体族样式的文本

Copy Div Content to Textarea or text with the same font-family style

本文关键字:文本 字体 样式 Div 复制 区域      更新时间:2023-09-26

我有一些代码可以将<div>的内容复制到<textarea>,但它不会复制<div>的样式(字体家族)。它以普通字体粘贴。我该如何解决这个问题?

HTML

<input type="text" id="styledText" placeholder="Place your Name..." size="50" name="styledText" class="changeMe">
<div id="fontselect" class="changeMe" onClick="copyText()" style="font-family: Times New Roman;font-size: 22px; font-weight: bold; cursor:pointer;">Place your Name...</div>

Javascript

function copyText() {
    var output = document.getElementById("fontselect").innerHTML;
    document.getElementById("styledText").value = output;
}

提前感谢:)

请记住,font-family将应用于插入文本的所有,因此任何单独样式的单词/内容都将失去其差异性:

function copyText() {
    var output = document.getElementById("fontselect"),
        textElem = document.getElementById("styledText");
    textElem.value = output.value;
    textElem.style.fontFamily = window.getComputedStyle(output,null).fontFamily || output.style.fontFamily || output.currentStyle.getCurrentProperty('font-family');
}
#fontselect, #styledText {
    font-family: Times New Roman;
    font-size: 22px;
    font-weight: bold;
    cursor:pointer;
}