Lui*_*ego 9 html javascript jquery copy
这是它:)我有id为一个div #toCopy,并与ID按钮#copy.按#copy时,将#toCopy内容复制到剪贴板的最佳方法是什么?
Han*_*ani 42
您可以复制到剪贴板,几乎在任何浏览器从输入元素只(元素具有.value属性),但你不能从相同的元素<div>,<p>,<span>...(元素具有.innerHTML属性).
但是我用这个技巧来做到这一点:
<textarea>innerHTML从<div>到新创建的<textarea>.value的<textarea>到剪贴板<textarea>我们刚刚创建的临时元素function CopyToClipboard (containerid) {
// Create a new textarea element and give it id='temp_element'
var textarea = document.createElement('textarea')
textarea.id = 'temp_element'
// Optional step to make less noise on the page, if any!
textarea.style.height = 0
// Now append it to your page somewhere, I chose <body>
document.body.appendChild(textarea)
// Give our textarea a value of whatever inside the div of id=containerid
textarea.value = document.getElementById(containerid).innerText
// Now copy whatever inside the textarea to clipboard
var selector = document.querySelector('#temp_element')
selector.select()
document.execCommand('copy')
// Remove the textarea
document.body.removeChild(textarea)
}Run Code Online (Sandbox Code Playgroud)
<div id="to-copy">
This text will be copied to your clipboard when you click the button!
</div>
<button onClick="CopyToClipboard('to-copy')">Copy</button>Run Code Online (Sandbox Code Playgroud)
不太晚但希望有所帮助!
| 归档时间: |
|
| 查看次数: |
21257 次 |
| 最近记录: |