【问题标题】:How can I get the ending drag position relative to the current frame?如何获得相对于当前帧的结束拖动位置?
【发布时间】:2017-05-17 00:45:26
【问题描述】:

我在 Google Chrome 中遇到了拖放问题:

foo.html:

<iframe style="position:absolute;left:300px" src="bar.html"></iframe>

bar.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 相对于当前帧属性的参数。

Here 是一个 jsfiddle,可以在 safari 或 chrome 上重现该问题。

编辑:澄清一下 - 在我的测试中,我不会在框架之外结束拖动。

【问题讨论】:

  • 你能说明输出应该与现在的输出进行比较吗?
  • 您的预期输出是什么?
  • 您的dragstart 总是出现在iframe 中,因此e.view 将始终等于iframe 的dragstart 窗口。但是,当您拖出 iframe 边界时,dragend 现在将位于 iframe 之外,因此 e.view 将等于您碰巧将其放入 iframe 父级的任何窗口。在这种情况下,拖动端的 e.clientX 和 e.clientY 位置对于父窗口来说是准确的。
  • @fmacdee 我添加了一个说明

标签: javascript html drag-and-drop draggable


【解决方案1】:

父窗口存储在 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();

在此之后,当您处理拖动事件时,请执行以下操作:

if(e.view == window) {
    xoff = e.clientX;
    yoff = e.clientY;
}
else {
    xoff = e.clientX - rect.left;
    yoff = e.clientY - rect.top;
}

这将为您提供相对于 iframe 的 x 和 y 位置。

【讨论】:

    【解决方案2】:

    如果 'ondragend' 事件在 iframe 之外触发,则该事件会冒泡到包含 iframe 的活动文档 ....

    出于安全原因,浏览器会阻止脚本尝试访问具有不同来源的框架 ....

    thread 中有关安全性的一些有用信息

    如果您也在后端工作,请尝试在 ondragstart 触发时将 clientX、clientY 值发布到后端并渲染您想要的页面,然后在 dragend 触发时获取相对位置...

    【讨论】:

      猜你喜欢
      • 2017-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-12
      相关资源
      最近更新 更多