<!DOCTYPE html>
<head>
<title> Query to Clipboard JS Applet by Damien Lesser </title>
</head>
<body>
<script type='text/javascript'>
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
if getQueryVariable('list') === null{
var clip = getQueryVariable('clip')
} else{
//Nothing
};
function copyStringToClipboard (str) {
// Create new element
var el = document.createElement('textarea');
// Set value (string to be copied)
el.value = clip;
// Set non-editable to avoid focus and move outside of view
el.setAttribute('readonly', '');
el.style = {position: 'absolute', left: '-9999px'};
document.body.appendChild(el);
// Select text inside element
el.select();
el.setSelectionRange(0, 99999); /* For mobile devices */
// Copy text to clipboard
document.execCommand('copy');
// Remove temporary element
document.body.removeChild(el);
};
copyStringToClipboard(clip);
var alert1 = 'copied '
var alert2 = ' to clipboard successfully'
console.log(alert1.concat(clip.concat(alert2)));
var para = document.createElement('p');
para.innerHTML = 'Copied successfully!'
</script>
</body>
</html>
正如您可能已经猜到的那样,我是 JavaScript 的新手,我正在尝试制作一个工具,允许开发人员打开带有查询字符串的 url,然后将查询用于剪贴板,在那些少数领域无法使用其他方法或经验不足的情况。它应该自动发生,但它不会产生任何结果。 如果您想对其进行测试,或者在我完成开发后使用此工具,只需转到 https://querytoclip.netlify.app/
然后添加'?clip='(不带引号) 到目前为止,除了我所要求的之外,如果有人能让我的代码更高效,那就太好了,因为我不是巫师...
答案 0 :(得分:0)
这可能对您有所帮助:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return (false);
}
if (getQueryVariable('list') === null) {
var clip = getQueryVariable('clip')
} else {
//Nothing
};
function copyStringToClipboard(str) {
// Create new element
var el = document.createElement('textarea');
// Set value (string to be copied)
el.value = clip;
// Set non-editable to avoid focus and move outside of view
el.setAttribute('readonly', '');
el.style = {
position: 'absolute',
left: '-9999px'
};
document.body.appendChild(el);
// Select text inside element
el.select();
el.setSelectionRange(0, 99999); /* For mobile devices */
// Copy text to clipboard
document.execCommand('copy');
// Remove temporary element
document.body.removeChild(el);
};
copyStringToClipboard(clip);
const contentDiv = document.getElementById("content");
var paragraph = document.createElement('p');
const paragraphContent = document.createTextNode("Copied successfully!");
paragraph.appendChild(paragraphContent);
document.body.insertBefore(paragraph, contentDiv);
答案 1 :(得分:0)
您的代码有很多问题,但除此之外,您在尝试在页面加载时复制到剪贴板时会遇到一些问题。
出于安全原因,许多 document.execCommand 命令需要用户交互(例如单击按钮)。复制就是这样一种方法。您可以向页面添加一个按钮,然后使用 @CLiown 响应在页面打开的位置进行一些工作,然后单击快速“复制”按钮。
欲了解更多信息,请阅读:
https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand