我有一個JavaScript應用程序,它將一個mousemove監聽器添加到文檔中。問題: 當鼠標移動到iframe上時,該函數不會被調用。從iframe接收mousemove事件
有沒有辦法將這些事件傳遞給根文檔?
我有一個JavaScript應用程序,它將一個mousemove監聽器添加到文檔中。問題: 當鼠標移動到iframe上時,該函數不會被調用。從iframe接收mousemove事件
有沒有辦法將這些事件傳遞給根文檔?
如果iframe中的文檔位於同一個document.domain中,則可以非常輕鬆地完成此操作。
如果您有相同的document.domain,您將不得不在iframe中設置mousemove偵聽器,並將值傳遞給父頁面。
如果文檔不在同一個document.domain中,它會變得相當複雜,並且您將需要iframes頁面來運行設置了mousemove事件偵聽器的javascript本身。然後您可以按照此處所述執行跨幀通信:http://softwareas.com/cross-domain-communication-with-iframes
否則,由於瀏覽器執行相同的原始策略,您將失去運氣。
我只是現在有同樣的問題,我想出了這個:
$("iframe").contents().find("body").mousemove(function(cursor){
$("#console").html(cursor.pageX+":"+cursor.pageY);
});
$(document).mousemove(function(cursor){
$("#console").html(cursor.pageX+":"+cursor.pageY);
});
.contents().find("body")
抓住的iframe裏面的內容和.mousemove()
可以用來添加事件偵聽器
HTML測試。 ..
<div id="console"></div>
你應該看看通過合併母公司document
事件與document.getElementById('iFrameId').contentDocument
結合事件中,女巫允許您訪問iFrame內容元素。
https://stackoverflow.com/a/38442439/2768917
function bindIFrameMousemove(iframe){
iframe.contentWindow.addEventListener('mousemove', function(event) {
var clRect = iframe.getBoundingClientRect();
var evt = new CustomEvent('mousemove', {bubbles: true, cancelable: false});
evt.clientX = event.clientX + clRect.left;
evt.clientY = event.clientY + clRect.top;
iframe.dispatchEvent(evt);
});
};
bindIFrameMousemove(document.getElementById('iFrameId'));
雖然指針事件:無;在樣式框架可以解決這個問題,但它禁止在iframe中的任何其他活動,我的解決辦法是切換就像值:
{{pointer-events : isMoving? 'none' : 'all' }}
好吧,那麼我必須用一個透明的股利,這是在這樣做iframe。 – 2011-03-10 14:48:46
我喜歡透明的div創意,但是如何將iframe中的鼠標事件傳遞迴父項? – Redtopia 2012-03-07 20:05:34
只需將它作爲參數傳遞給您所選擇的函數調用即可:) – 2012-03-07 22:09:46