开发者问题收集

setTimeout 并将按钮值复制到剪贴板

2019-02-05
1058

我有一个按钮,我想在鼠标悬停在按钮上一秒钟后将其值复制到剪贴板,如果可以避免的话,只使用 javascript, 而不是 jQuery

这段代码有两个问题:

  1. setTimeout 不起作用——警报立即发生,无需等待一秒钟,并且
  2. 我收到“TypeError:null 不是对象(评估‘document.getElementById(obj).value’)”错误
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);" />
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);" />
Alen.Toma
2019-02-05

如果您获得权限,则可以执行此操作 - 来自其他答案的想法,但未正确实施

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" />
mplungjan
2019-02-05