将事件处理程序添加到iframe以在keyup上调用 [英] Adding event handler to iframe to invoke on keyup

查看:114
本文介绍了将事件处理程序添加到iframe以在keyup上调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在网页上我有iframe,我在其中显示了一些内容。

如果在iframe中按下了任何键,我想运行一个函数(iframe是可编辑的)。

On the webpage I have iframe, in which I display some content.
I want to run a function if any key is pressed inside iframe (iframe is editable).

我可以使用ajax(页面上有scriptmanager)来实现:

I can do it using ajax (with scriptmanager on page):

Sys.UI.DomEvent.addHandler(document.getElementById('iframe1').contentWindow.document, 'keyup', iframeKeyHandler);

但我想在没有ajax的情况下这样做!

But I want to do it without ajax!

更新代码:

function Init() {
    document.getElementById('iView').contentWindow.document.designMode = "on";       

     document.getElementById('iView').contentWindow.document.onkeyup = function(event) {
       alert(event);
     }    
 }

<body onload="Init()" >   
<iframe id="iView" style="width: 434px; height:371px" ></iframe>
</body> 


推荐答案

我想你的意思是不使用脚本就行经理?

I guess you meant "do it without using the script manager"?

你可以这样做(使用 attactEvent / addEventListener ):

You can do it this way (use attactEvent/addEventListener):

<html>
<head>
<script type="text/javascript">
function Init() {
    var _win = document.getElementById("iView").contentWindow;
    var _doc = _win.document;
    _doc.designMode = "on";
    if(_doc.addEventListener) {// if support addEventListener
        _doc.addEventListener("keyup", frameKeyUp, true)
    }
    else { //For IE
        _doc.attachEvent("onkeyup", frameKeyUp);
    }
}
function frameKeyUp(e){
    alert(e.keyCode);
}
</script>
</head>
<body onload="Init()" >   
<iframe id="iView" style="width: 434px; height:371px"></iframe>
</body>
</html>

或者使用jQuery的 keyup 的nofollow noreferrer>事件处理程序:

Or using jQuery's event handler for "keyup":

$('#iframe1').keyup(function(event){
  //... do your stuff here ..
  //use event.keyCode to get the asscoiated key
});

有关键盘事件arg的更多信息可以找到这里这里

More info on keyboard event arg can be found here and here.

这篇关于将事件处理程序添加到iframe以在keyup上调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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