>我在谷歌浏览器中遇到了拖放问题:
foo.html :
<iframe style="position:absolute;left:300px" src="bar.html"></iframe>
酒吧.html :
<div draggable="true" id="bar">Drag me!</div>
<script>
document.getElementById("bar").addEventListener("dragend", function(e) {
console.log(e.view === window); // false
console.log(e.view === window.parent); // true
});
</script>
为什么e
相对于父窗口而不是当前窗口(即当前框架的window
属性(?我已经确认dragstart
和dragover
都接收具有相对于当前帧view
属性的参数。
这是一个 jsfiddle,可以在 safari 或 chrome 上重现该问题。
编辑:澄清一下 - 在我的测试中,我没有结束框架外的拖动。
父窗口存储在 e.view 中的原因是因为拖拽发生在 iframe 之外。如果您想知道 iframe 相对于窗口的位置,那么只要两个文件位于同一服务器上,您就可以这样做,这样保护父窗口就不会有跨源问题。如果这是真的,那么您可以执行以下操作:
// get the iframes from the parent
var iframes = window.parent.document.getElementsByTagName('iframe');
var iframe;
// search through the iframes[] array and match your name
for (var i = 0; i < iframes.length; i++) {
if (iframes[i].src == 'bar.html') { // note, you may have to parse this or add your full pathname
iframe = iframes[i];
break;
}
}
// get the boundaries of the selected iframe
var rect = iframes[i].getBoundingClientRect();
在此之后,在处理 dragend 事件时,请执行以下操作:
if(e.view == window) {
xoff = e.clientX;
yoff = e.clientY;
}
else {
xoff = e.clientX - rect.left;
yoff = e.clientY - rect.top;
}
这将为您提供相对于 iframe 的 x 和 y 位置。
如果在 iframe 外部触发了"ondragend"事件,则该事件将冒泡到包含 iframe 的活动文档 ....
由于安全原因,浏览器会阻止脚本尝试访问具有不同来源的框架....
有关此线程中安全性的一些有用信息
如果您也在后端工作,请尝试在 ondragstart 触发时将 clientX,clientY 值发布到后端并渲染您想要的页面,然后在 dragend 触发时获取相对位置......