在Javascript(Google Docs)中捕获按键 [英] Capture keypress in Javascript (Google Docs)

查看:212
本文介绍了在Javascript(Google Docs)中捕获按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一些关于每个文档的例子/ bookmarklet / Google文档。我想添加的功能需要一个keypress / keyup / keydown事件处理程序(这三个中的一个)。不幸的是,Javascript不是我的强项,而且我似乎无法在编辑窗格中捕获(?)一个按键事件。作为最后的手段,我尝试了以下内容:

I'm trying to write a little greasemonkey script/bookmarklet/what have you for Google Docs. The functionality I'd like to add needs a keypress/keyup/keydown event handler (one of those three). Unfortunately, Javascript isn't my forté, and I can't seem to capture (?) a keypress event to while in the edit pane. As a last resort, I've tried the following:

javascript:(function(){
  els = document.getElementsByTagName("*");
  for(i=0;i<els.length;i++){
    els[i].onkeypress=function(){alert("hello!");};
    els[i].onkeyup=function(){alert("hello2!");};
    els[i].onkeydown=function(){alert("hello3!");};
  }
})();

然而,这仍然无法捕获编辑窗格中的按键 - 没有烦人的警报(尽管似乎为大多数其他网站工作...)。我已经检查了Chrome和Firefox两者(我无法在任何一个中使用它)。

However, this still doesn't capture keypresses in the editing pane - no annoying alerts (although it seems to work for most other sites...). I've checked in Chrome and Firefox both (I can't get it to work in either one).

我在Firebug中尝试了Log Events(并检查出来)所有注册的活动都通过一个整齐的小扩展到Firebug,Eventbug);似乎这些事件并没有在按键上发射。

I tried "Log Events" in Firebug (and checked out all the registered events via a neat little extension to Firebug, Eventbug); it didn't seem like those events were firing on keypresses.

编辑:

为了澄清[Tim],我做了这个屏幕截图带有一些注释...


To clarify [Tim], I made this screenshot with some annotations...

我正在谈论的编辑窗格似乎是一堆Javascripted-up div显示我键入的内容。

The "editing pane" I'm talking about seems to be a bunch of Javascripted-up divs displaying what I type.

任何想法?谢谢!

推荐答案

在Google文档中编辑使用iframe。您需要将监听器附加到iframe的文档。它似乎做了一些复杂的iframe我还没有完全解决,但以下似乎适用于Firefox:

Editing in Google Docs uses an iframe. You need to attach a listener to the iframe's document. It seems to do something complicated with the iframe I haven't yet been able to work out fully, but the following seems to work for Firefox:

var iframe = document.getElementsByTagName("iframe")[0];
if (iframe) {
    iframe.contentDocument.addEventListener("keypress", function(evt) {
        console.log("iframe keypress: " + evt.which);
    }, false);
}

这篇关于在Javascript(Google Docs)中捕获按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆