如何使用javascript和/或jquery从父窗口访问iframes文档事件鼠标位置 [英] How can I access an iframes document event mouse position from the parent window using javascript and or jquery
问题描述
我在父窗口中有一个iframe,iframe src和父窗口位于同一个域中。为了保持iframe文档不受javascript限制,我希望能够在父窗口中使用一个函数来获取iframe中的鼠标位置。
I have an iframe inside of a parent window, with both the iframe src and the parent located in the same domain. In order to keep the iframe document clear of javascript I want to be able to use a function in the parent window to get the the mouse position inside the iframe.
我的尝试到目前为止,包括:
My attempts at this so far have included:
<iframe id="iframe1" src="test.html" style="position:relative; width:500px; height:500px"></iframe>
<div id="result" style="border:1px solid black"></div>
<script>
$(document).bind("mousemove", function(e){
$("#result").html("x:" + e.pageX + ", y:" + e.pageY);
});
$("#iframe1").contents().find(document).bind("mousemove", function(e){
$("#result", window.parent.document).html("x:" + e.pageX + ", y:" + e.pageY);
});
</script>
第一个mousemove事件正常显示结果div中的鼠标位置,但是第二个事件(我试图绑定到iframe文档)没有给出任何响应。
The first mousemove event works correctly displaying the mouse position in the results div, but the second event (which I was attempting to bind to the iframe document) gives no response.
推荐答案
此有效,但权限部分除外。
This works, except for the permissions part.
JS:
$(document).bind("mousemove", function(e) {
$("#result").html("x:" + e.pageX + ", y:" + e.pageY);
});
$($("#iframe1").contents()[0], window).bind("mousemove", function(e) {
$("#result").html("x:" + (e.pageX) + ", y:" + e.pageY);
});
问题在于 .find()
。我只是使用内容返回的数组上的第一个索引,因为iframe应该只包含文档。
The problem was with .find()
. I simply used the first index on the array returned by content, because an iframe is supposed to contain nothing but a document.
更新了一个更好的例子。
Updated with a better example.
这篇关于如何使用javascript和/或jquery从父窗口访问iframes文档事件鼠标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!