How can I access an iframes document event mouse p

2019-05-21 09:14发布

问题:

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>

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.​

回答1:

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);
});

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.