在本文中,我将深入解释 30秒代码中 的copyToClipboard代码段如何 工作。 您可以在项目的存储库中找到它的源代码以及大量其他有用的方法。
30秒的代码:您可以在30秒或更短的时间内理解的Java 代码片段
网站建设中经常出现的一件事是能够将一些文本复制到剪贴板,而无需用户选择它或敲击键盘上的适当组合键。 Javascript可以通过五个短步轻松完成此操作:
- 创建一个
<textarea>
元素添加到文档中。 将其value
设置为我们要复制到剪贴板的字符串。 - 将所述
<textarea>
元素追加到当前HTML文档中。 - 使用
HTMLInputElement.select()
选择<textarea>
元素的内容。 - 使用
Document.execCommand('copy')
将<textarea>
的内容复制到剪贴板。 - 从文档中删除
<textarea>
元素。
此方法的最简单版本应如下所示:
const copyToClipboard = str => {
const el = document .createElement( 'textarea' );
el.value = str;
document .body.appendChild(el);
el.select();
document .execCommand( 'copy' );
document .body.removeChild(el);
};
(copyToClipboard方法的基本实现)
请记住,由于Document.execCommand()
工作方式,该方法不会在所有地方都有效,而只能是由于用户操作(例如在click
事件侦听器内部)导致的。
使附加元素不可见
如果尝试上述方法,则在添加<textarea>
元素然后将其删除后,可能会看到一些闪烁。 这个问题对于在屏幕阅读器上的人们来说尤其糟糕,因为它可能会引起一些非常烦人的问题。 因此,下一步的逻辑步骤是使用一些CSS使该元素不可见,并将其变为readonly
,以防用户尝试弄乱它:
const copyToClipboard = str => {
const el = document .createElement( 'textarea' );
el.value = str;
el.setAttribute( 'readonly' , '' );
el.style.position = 'absolute' ;
el.style.left = '-9999px' ;
document .body.appendChild(el);
el.select();
document .execCommand( 'copy' );
document .body.removeChild(el);
};
(没有显示文本区域的copyToClipboard实现)
保存和还原原始文档的选择
最后要考虑的是,用户可能已经选择了HTML文档上的某些内容,因此最好不要删除他们可能选择的任何内容。 幸运的是,我们现在可以使用一些现代的Javascript方法和属性,例如DocumentOrShadowRoot.getSelection()
, Selection.rangeCount
, Selection.getRangeAt()
, Selection.removeAllRanges()
和Selection.addRange()
来保存和恢复原始文档选择。 这是实现这些改进的带有注释的最终代码:
const copyToClipboard = str => {
const el = document .createElement( 'textarea' ); // Create a <textarea> element
el.value = str; // Set its value to the string that you want copied
el.setAttribute( 'readonly' , '' ); // Make it readonly to be tamper-proof
el.style.position = 'absolute' ;
el.style.left = '-9999px' ; // Move outside the screen to make it invisible
document .body.appendChild(el); // Append the <textarea> element to the HTML document
const selected =
document .getSelection().rangeCount > 0 // Check if there is any content selected previously
? document .getSelection().getRangeAt( 0 ) // Store selection if found
: false ; // Mark as false to know no selection existed before
el.select(); // Select the <textarea> content
document .execCommand( 'copy' ); // Copy - only works as a result of a user action (e.g. click events)
document .body.removeChild(el); // Remove the <textarea> element
if (selected) { // If a selection existed before copying
document .getSelection().removeAllRanges(); // Unselect everything on the HTML document
document .getSelection().addRange(selected); // Restore the original selection
}
};
(带有选择存储的copyToClipboard的最终形式)
这几乎就是它的全部。 在不到20行的代码中,我们创建了前端开发中最常用的方法之一。
如果您喜欢本文,请查看 30秒的代码, 以获取有关Javascript项目的更有用的代码段!
From: https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f