我知道我们可以使用如下绑定粘贴事件:
$('#id').bind('paste', function(e) {
alert('pasting!')
});
但问题是,它会在粘贴的文本粘贴之前调用。我希望在右键单击后触发一个函数- >粘贴粘贴在输入字段上的文本,以便我可以访问事件处理函数中的粘贴值。
.change()
事件也无济于事。目前我使用.keyup()
事件,因为我需要在输入该输入字段时显示剩余字符数。
我知道我们可以使用如下绑定粘贴事件:
$('#id').bind('paste', function(e) {
alert('pasting!')
});
但问题是,它会在粘贴的文本粘贴之前调用。我希望在右键单击后触发一个函数- >粘贴粘贴在输入字段上的文本,以便我可以访问事件处理函数中的粘贴值。
.change()
事件也无济于事。目前我使用.keyup()
事件,因为我需要在输入该输入字段时显示剩余字符数。
有点黑客,但是:
$("#id").bind('paste', function(e) {
var ctl = $(this);
setTimeout(function() {
//Do whatever you want to $(ctl) here....
}, 100);
});
为什么不使用“输入”事件?
$("#id").bind('input', function(e) {
var $this = $(this);
console.log($this.val());
});
这将阻止用户使用键盘进行任何粘贴、处理或剪切:
$("#myField").keydown(function(event) {
var forbiddenKeys = new Array('c', 'x', 'v');
var keyCode = (event.keyCode) ? event.keyCode : event.which;
var isCtrl;
isCtrl = event.ctrlKey
if (isCtrl) {
for (i = 0; i < forbiddenKeys.length; i++) {
if (forbiddenKeys[i] == String.fromCharCode(keyCode).toLowerCase()) {
return false;
}
}
}
return true;
});
这将对鼠标事件执行相同的操作:
$("#myField").bind("cut copy paste",function(event) {
event.preventDefault();
});
即使上述内容不会阻止右键单击,用户也无法从该字段粘贴、剪切或复制。
要在事件之后使用它,就像您想知道的那样,您必须使用JavaScript Timing Event
setTimeout(function() {
// your code goes here
}, 10);
我遇到了同样的问题,我选择通过 javascript 复制粘贴操作并改用该输出:
var getPostPasteText = function (element, pastedData) {
// get the highlighted text (if any) from the element
var selection = getSelection(element);
var selectionStart = selection.start;
var selectionEnd = selection.end;
// figure out what text is to the left and right of the highlighted text (if any)
var oldText = $(element).val();
var leftPiece = oldText.substr(0, selectionStart);
var rightPiece = oldText.substr(selectionEnd, oldText.length);
// compute what the new value of the element will be after the paste
// note behavior of paste is to REPLACE any highlighted text
return leftPiece + pastedData + rightPiece;
};
请参阅IE 的 document.selection.createRange 不包括getSelection
函数源的前导或尾随空行。
无需绑定:
$(document).on('keyup input', '#myID', function () {
//Do something
});