右键单击并粘贴触发事件 [英] Fire event with right mouse click and Paste
问题描述
我想在文本区域中粘贴一些文本后立即在文本区域中触发事件.使用Shift + Ins时可以做到这一点;但是,我不能这样做,当鼠标右键,然后(从下拉菜单)选择粘贴. Shift + Ins之后触发Keyup.在单击鼠标右键后选择粘贴"后,其余所有内容均不会触发...我该怎么办?
I want to fire an event in a textarea immediately after paste some text inside the textarea. I can do that when Shift+Ins is used; however, I cannot do it when right mouse button and then paste (from the drop down menu) is chosen. Keyup fires after Shift+Ins. None of the rest fires when Paste is chosen after right mouse button clicking... What do I have to do?
<textarea name="message" id="message"></textarea>
$("#message").on('keyup contextmenu', function(event) {
alert("ok");
});
http://jsfiddle.net/f29vuwoL/7/
谢谢
推荐答案
大多数浏览器都支持input
事件,该事件在粘贴或以其他方式添加时触发,无论如何:
Most browsers support the input
event, which is fired when something is pasted or otherwise added, regardless of how:
$("#message").on('keyup contextmenu input', function(event) {
alert("ok");
});
请注意,使用input
是最通用的方法,无论控件如何获取输入都会触发,因此,如果挂接多个事件(如上所述),则将对同一输入进行多次调用.例如,如果在支持input
的浏览器上同时钩住keyup
和input
,则会收到两个调用.当用户粘贴时,对于同时支持paste
和input
的浏览器,同样适用.
Note that using input
is the most general method, firing when the control gets input regardless of how, and so if you hook multiple events (as above), you'll get multiple calls for the same input. For instance, if you hook both keyup
and input
, on browsers that support input
, you'll get two calls. Similarly for paste
and input
when the user pastes, on browsers that support both.
如果您需要支持没有input
或paste
的浏览器,恐怕不幸的答案是您需要轮询.不过,每隔250毫秒进行一次轮询并不会要求浏览器完成那么多工作,因此您可以通过功能检测是否有必要:
If you need to support browsers that don't have either input
or paste
, I'm afraid the unfortunate answer is that you need to poll. Still, polling every (say) 250ms isn't asking the browser to do that much work, and you can feature-detect whether it's necessary:
var message = $("#message");
var events = null;
var previous;
if ('oninput' in message[0]) {
// Browser supports input event
events = "input";
} else if ('onpaste' in message[0]) {
// Browser supports paste event
events = "paste keyup contextmenu";
}
if (!events) {
// Ugh, poll and fire our own
events = "pseudoinput";
previous = message.val();
setInterval(function() {
var current = message.val();
if (current != previous) {
previous = current;
message.trigger(events);
}
}, 250);
}
console.log("Using: " + events);
message.on(events, function(e) {
console.log("Got event: " + e.type);
});
这篇关于右键单击并粘贴触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!