3 回答

TA貢獻1895條經驗 獲得超3個贊
您可以通過附加“ onpaste”處理程序來攔截粘貼事件,并通過window.clipboardData.getData('Text')在IE中使用“ ”或event.clipboardData.getData('text/plain')在其他瀏覽器中使用“ ” 來獲取粘貼的文本。
例如:
var myElement = document.getElementById('pasteElement');
myElement.onpaste = function(e) {
var pastedText = undefined;
if (window.clipboardData && window.clipboardData.getData) { // IE
pastedText = window.clipboardData.getData('Text');
} else if (e.clipboardData && e.clipboardData.getData) {
pastedText = e.clipboardData.getData('text/plain');
}
alert(pastedText); // Process and handle text...
return false; // Prevent the default handler from running.
};
如@pimvdb所述,e.originalEvent.clipboardData如果使用jQuery ,則需要使用“ ”。

TA貢獻1859條經驗 獲得超6個贊
我需要對粘貼的內容執行“修剪”操作(刪除所有前導和尾隨空格),同時仍然允許使用空格鍵。
對于Ctrl + V,Shift + Insert和鼠標右鍵單擊“粘貼”,這是我發現自2017年4月22日起在FF,IE11和Chrome中起作用的內容:
$(document).ready(function() {
var lastKeyCode = 0;
$('input[type="text"]').bind('keydown', function(e) {
lastKeyCode = e.keyCode;
});
// Bind on the input having changed. As long as the previous character
// was not a space, BS or Del, trim the input.
$('input[type="text"]').bind('input', function(e) {
if(lastKeyCode != 32 && lastKeyCode != 8 && lastKeyCode != 46) {
$(this).val($(this).val().replace(/^\s+|\s+$/g, ''));
}
});
});
兩個警告:
如果粘貼時已經有文本,則會在整個結果上進行修剪,而不僅僅是粘貼內容。
如果用戶鍵入空格或BS或Del,然后粘貼,則不會進行修剪。
添加回答
舉報