将Div内容复制到Textarea或具有相同font-family样式的文本

时间:2012-09-04 15:05:36

标签: javascript html

我有一些代码会将<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;
}

提前致谢:)

2 个答案:

答案 0 :(得分:2)

请注意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');

}

答案 1 :(得分:0)

#fontselect, #styledText {
    font-family: Times New Roman;
    font-size: 22px;
    font-weight: bold;
    cursor:pointer;
}