【问题标题】:Onpaste is only triggered by keyboard pasteOnpaste 仅由键盘粘贴触发
【发布时间】:2018-05-24 10:06:48
【问题描述】:

我有这个代码:

<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

【问题讨论】:

  • 我尝试将事件输出到这样的控制台:&lt;input type="text" id="point-setter-input" onkeyup="console.log('keyup')" onpaste="console.log('onpaste')" value="0"&gt; &lt;span class="api command initialized" data-command-name="SetPoints" data-events="click" data-container="#popup-content" id="point-setter-span" data-data="data=3"&gt;Pontok Mentése&lt;/span&gt;,它工作正常。 onpaste 甚至早于 onkeyup...

标签: javascript html paste


【解决方案1】:

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

所以当你检查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);
}
&lt;input type="text" id="inp"&gt;

【讨论】:

    【解决方案2】:

    我已经使用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">
    

    【讨论】:

      猜你喜欢
      • 2011-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-06
      • 2011-01-20
      • 1970-01-01
      相关资源
      最近更新 更多