Onpaste 仅由键盘粘贴触发

Onpaste is only triggered by keyboard paste

我有这个代码:

<input type="text" id="point-setter-input" onkeyup="if (!isNaN(this.value)) {document.getElementById('point-setter-span').setAttribute('data-data', 'data=' + this.value)};" onpaste="if (!isNaN(this.value)) {document.getElementById('point-setter-span').setAttribute('data-data', 'data=' + this.value)};" value="0">
<span class="api command initialized" data-command-name="SetPoints" data-events="click" data-container="#popup-content" id="point-setter-span" data-data="data=3">Pontok Mentése</span>

每当 inputvalue 通过 onkeyup 更改时,spandata-data 将获取该值(如果它恰好是一个数字) .然而,onpaste永远不会运行。如果我通过键盘粘贴,那么 spandata-data 将成功更新,但这只是因为我的 onkeyup,也就是说,如果我没有那个属性,即使用键盘粘贴不会 运行。为什么 onpaste 在我的案例中不起作用?我已经在 Chrome 和 Firefox 中检查过了。

编辑

原来执行了onpaste,但是value不是粘贴的文本。我认为这里需要一个丑陋的解决方案,涉及 setTimeout.

粘贴事件在设置 <input> 的值之前触发,否则您无法阻止其默认行为(即设置 <input> 的值)。

所以当你检查if(!isNaN(this.value))时,粘贴事件中包含的新值仍然没有设置。

要解决此问题,只需监听 input 事件,该事件在任何情况下都会被触发。

var inp = document.getElementById('inp');
inp.onpaste = function() {
  console.log('paste', this.value);
};
inp.oninput = function() {
  console.log('input', this.value);
}
<input type="text" id="inp">

我已经使用setTimeout解决了这个问题,所以我使用它时更改了值:

<input type="text" id="point-setter-input" onkeyup="setTimeout(() => {if (!isNaN(this.value.trim())) {document.getElementById('point-setter-span').setAttribute('data-data', 'data=' + this.value)};}, 4);" onpaste="setTimeout(() => {if (!isNaN(this.value.trim())) {document.getElementById('point-setter-span').setAttribute('data-data', 'data=' + this.value)};}, 4);" value="0">