我正在使用highlight.js,生成了一個塊:
<pre class="code code-javascript"><label>JS</label><code class="language-javascript">equation_app.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-params">e</span>=></span>{
autofocus(e);
<span class="hljs-keyword">let</span> start = editor.selectionStart;
<span class="hljs-keyword">let</span> end = editor.selectionEnd;
tagging(<span class="hljs-string">'$'</span>, <span class="hljs-string">'$'</span>);
editor.focus();
<span class="hljs-keyword">if</span>(editor.selectionStart === editor.selectionEnd)editor.selectionStart = editor.selectionEnd = start <span class="hljs-number">1</span>;
refresh();
});</code><div class="copy">click to copy</div></pre>
我制作了一個按鈕,單擊以將文本復制到用戶的剪貼板。
function copy_to_clipboard(stritem){
const el = document.createElement('textarea');
el.value = stritem;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
window.alert('Successfully copied to your clipboard!');
}
但是,我不能直接呼叫,copy_to_clipboard(codeElement.innerHTML)因為所有 html 樣式的東西都被復制進來了。
我想知道是否有一種方法可以從樣式化的 Dom<code>元素中提取干凈的代碼
uj5u.com熱心網友回復:
而不是使用innerHTML使用textContent像:
function copy_to_clipboard() {
const el = document.createElement('textarea');
el.value = document.querySelector('code').textContent;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
window.alert('Successfully copied to your clipboard!');
}
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.2.0/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.2.0/highlight.min.js"></script>
<pre class="code code-javascript">
<label>JS</label>
<code class="language-javascript">
equation_app.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-params">e</span>=></span>{
autofocus(e);
<span class="hljs-keyword">let</span> start = editor.selectionStart;
<span class="hljs-keyword">let</span> end = editor.selectionEnd;
tagging(<span class="hljs-string">'$'</span>, <span class="hljs-string">'$'</span>);
editor.focus();
<span class="hljs-keyword">if</span>(editor.selectionStart === editor.selectionEnd)editor.selectionStart = editor.selectionEnd = start <span class="hljs-number">1</span>;
refresh();
});
</code>
<div class="copy" onclick="copy_to_clipboard()">click to copy</div>
</pre>
參考:
- 文本內容
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/317297.html
標籤:javascript html 高亮js
上一篇:視窗最小化時網頁未顯示完整內容
