我有一个按钮,如果要避免这种情况,我想仅将鼠标悬停在鼠标上一秒钟,然后将其值复制到剪贴板上,而不使用jQuery 。 / p>
此代码有两个问题:
function getButtonValue(obj) {
document.getElementById(obj).value.execCommand("copy");
alert("\"" + obj.value + "\" has been copied to the clipboard.");
} // function getid(obj)
<input type="button" id="button2" value="bite me" onmouseover="setTimeout(getButtonValue(this), 1000);" />
答案 0 :(得分:2)
您正在调用方法,而不是将其分配给settimeout
这是您要怎么做
function getButtonValue(obj) {
obj.focus();
obj.select();
const result = document.execCommand('copy');
if (result === 'unsuccessful' || result == false) {
console.log('Failed to copy text.');
}
} // function getid(obj)
<input type="button" id="button2" value="bite me" onmouseover="setTimeout(()=> getButtonValue(this), 1000);" />
答案 1 :(得分:1)
如果获得许可,您可以执行此操作-来自其他未正确实施的答案的想法
https://developers.google.com/web/updates/2018/03/clipboardapi
var tId = "";
navigator.permissions.query({
name: 'clipboard-read'
}).then(permissionStatus => {
// Will be 'granted', 'denied' or 'prompt':
console.log(permissionStatus.state);
// Listen for changes to the permission state
permissionStatus.onchange = () => {
console.log(permissionStatus.state);
};
})
document.getElementById("button2").addEventListener("mouseover", function(e) {
var val = this.value;
setTimeout(function() {
navigator.clipboard.writeText(val)
.then(() => console.log(val + " copied"))
.catch(err => {
// This can happen if the user denies clipboard permissions:
console.error('Could not copy text: ', err);
});
}, 1000)
})
document.getElementById("button2").addEventListener("mouseout", function() {
clearTimeout(tId);
});
<input type="button" id="button2" value="bite me" />