我想选择onclick td的innerHTML,这样用户就可以执行ctrl C来复制内容.
我尝试了很多组合,我找不到办法.然而,它接口使用简单的document.getElementById(id).select();
document.getElementById(…).select is not a function
那么我怎么能用td元素呢?
我不介意它是否不适用于IE.
或者,如果可能,直接复制文本.
最佳答案
复制并不难.我使用这个功能,这也适用于其他浏览器,而不仅仅是IE(来源未知).
https://jsfiddle.net/5bhkydq1/
javascript和jquery
$('div').click(function(){
copyTextToClipboard($(this).html());
});
function copyTextToClipboard(text) {
var textArea = document.createElement("textarea");
// Place in top-left corner of screen regardless of scroll position.
textArea.style.position = 'fixed';
textArea.style.top = 0;
textArea.style.left = 0;
// Ensure it has a small width and height. Setting to 1px / 1em
// doesn't work as this gives a negative w/h on some browsers.
textArea.style.width = '2em';
textArea.style.height = '2em';
// We don't need padding,reducing the size if it does flash render.
textArea.style.padding = 0;
// Clean up any borders.
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.BoxShadow = 'none';
// Avoid flash of white Box if rendered for any reason.
textArea.style.background = 'transparent';
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops,unable to copy');
}
document.body.removeChild(textArea);
}