2015-11-05 125 views
1

我知道有一百万篇关于如何将javascript变量复制到剪贴板的帖子。我偏向于这种方法:如何将格式化文本复制到剪贴板

window.prompt("Copy to clipboard: Ctrl+C, Enter", output); 

但是,我想知道如何可以得到一个包含粗体的变量。我希望的结果是,我可以将变量粘贴到文字中,并将其一部分粗体显示。我试图建立像这样的变量:

var output = "something <b>bold section</b> something else"; 

我不想字面上导出为HTML,我想导出它,就好像我选择,然后复制以下内容:

东西加粗部分别的东西

我该如何最好地实现这个结果?

+0

[某种方式与(http://stackoverflow.com /问题/ 17470817 /格式的文本功能于JavaScript的警告框) – Kaiido

回答

0

我觉得you can't风格的提示窗口。

但是一个可能的方式,对于recent browsers(IE9 +),是使用Selection API代替prompt()招:

btn.onclick = function() { 
 
    // create a modal 
 
    var p = document.createElement('p'); 
 
    p.innerHTML = "something <b>bold section</b> something else"; 
 
    document.body.appendChild(p); 
 
    // create a new range of our message 
 
    var range = document.createRange(); 
 
    // get the textNodes 
 
    var nodes = p.childNodes; 
 
    // start our range at first node 
 
    range.setStart(nodes[0], 0); 
 
    // end it at last 
 
    range.setEnd(nodes[nodes.length - 1], nodes[nodes.length - 1].length); 
 
    // create a Selection object 
 
    var sel = getSelection(); 
 
    // remove existing ranges 
 
    sel.removeAllRanges() 
 
    // set our new one 
 
    sel.addRange(range); 
 
}
<button id="btn">show the text to copy</button>