【发布时间】:2017-09-22 07:30:20
【问题描述】:
在跨浏览器 Javascript 中,如何在 <input> 元素的值因文本被拖放到字段中而发生更改后获取事件?
input.addEventListener("change", cb); // Is not triggered on drop
input.addEventListener("drop", cb); // Is triggered before the value change
一个sn-p来演示问题:
let input = document.getElementById('input');
let button = document.getElementById('button');
let div = document.getElementById('div');
function log(msg) {
let el = document.createElement('pre');
el.textContent = msg;
div.appendChild(el);
}
input.addEventListener("change", function() {
log("CHANGE: " + input.value);
});
input.addEventListener("keyup", function() {
log("KEYUP: " + input.value);
});
input.addEventListener("drop", function() {
log("DROP: " + input.value);
});
button.addEventListener("click", function() {
log("CLICK: " + input.value);
});
log("Try dragging text into the input field");
<input id="input"></input>
<button id="button">Click</button>
<div id="div"></div>
【问题讨论】:
-
我发现了一种至少适用于 Chrome 的解决方法:在读取值之前在 drop 上触发
setTimeout(cb, 0)。 -
我使用 setTimeout 尝试了您的解决方法,它也在 firefox 中工作
标签: javascript html input drag-and-drop dom-events