[英]Get value change event on drop to input element
在跨瀏覽器Javascript中,由於將文本拖放到字段中而更改了<input>
元素的值后,如何獲取事件?
input.addEventListener("change", cb); // Is not triggered on drop
input.addEventListener("drop", cb); // Is triggered before the value change
演示該問題的代碼段:
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>
您可以使用getData方法獲取所刪除數據的文本值:
// This will get the current data value dropped as a string
event.dataTransfer.getData("text");
並防止通過以下方式在輸入中設置相同的值:
// This will prevent the input to be changed with the dropped data
event.preventDefault();
因此完整的事件處理程序將如下所示:
input.addEventListener('drop', function (event) {
event.preventDefault();
var textData = event.dataTransfer.getData('text');
// do whatever you want with the the text data
});
因此,您可以嘗試從drop事件中截取數據並對其進行處理,而不是試圖在正確的時刻獲取輸入值。 您甚至可以稍后將其設置為文本。
讓我知道它是否可以解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.