Javascript DOM将值发送到iframe中嵌入的函数来模拟keypress

时间:2014-01-10 19:50:53

标签: javascript html dom iframe

我有一个测试,我一直在努力,尝试将值发送到iframe中定义的函数(来自同一来源的两个页面)。处于焦点时iframe的内容响应某些击键。我想要实现的是通过主页面上的按钮从iframe触发那些按键操作。

iframe的内容是动态的,需要在没有刷新的情况下运行,否则我知道我可以更改iframe src来携带变量。我到目前为止......

父页面:

<!DOCTYPE html><html><head>
<style>
  iframe{border:1px solid blue;height:100px;width:100px;margin:20px auto 0 auto;}
</style>
</head><body>
<iframe id="iframe" src="iframetest2.html"></iframe>
<button onclick="simKey(32);">CLICK</button>
<script>
  var iframe=document.getElementById('iframe');
  var ifContent=iframe.contentWindow
  function simKey(x){
    ifContent.postMessage(testScript(x),'*','[transfer]');
  }
</script></body></html>

iFrame内容:

<!DOCTYPE html><html><head>
<script>
  function testScript(x){
document.body.innerHTML=x;
setTimeout(function(){document.body.innerHTML='';},700);
  }
  </script></head><body onkeypress="testScript(event.keyCode)"></body></html>

我也试图尽可能避免使用jQuery。这是一个概念网页设计,真的很想手工编写Javascript,以便我可以根据需要进行修改。

1 个答案:

答案 0 :(得分:3)

首先,内联js(如html中的onkeypress)是一种不好的做法。阅读以下结果:https://www.google.com/search?q=Why+is+inline+js+bad%3F

我将使用最佳做法addEventListener

从父窗口按钮触发iFrame按键事件:

Live demo (click).

主页:

var myBtn = document.getElementById('myBtn');
var iframe = document.getElementById('myIframe');

myBtn.addEventListener('click', function() {
  var evt = new Event('keypress');
  evt.keyCode = '115';
  iframe.contentDocument.body.dispatchEvent(evt);
});

<强>的iFrame:

document.body.addEventListener('keypress', function(e) {
  console.log(e.keyCode);
});

如果您需要支持旧浏览器或想了解更多信息,以下是一些可能对您有所帮助的文档:https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

旧答案:这会侦听父窗口上的按键。

在iFrame中,您只需要拥有此JavaScript:

window.parent.document.body.addEventListener('keypress', function(e) {
  console.log(e.keyCode);
});