jQuery and iframes and weird positioning: is there

2020-02-14 03:49发布

问题:

I've got a draggable thing outside an iframe, and a droppable target inside it. Here I've shown the iframe as containing a snippet of the HTML that is loaded by its src attribute.

<div id="draggables">
  <img src="drag-me.gif">
</div>

<iframe src="iframe-src.html" id="iframe">
  <!-- HTML gubbins -->

  <div id="droppable">&nbsp;</div>

  <!-- More HTML gubbins -->
</iframe>

I use some jQuery (UI draggable/droppable) to do stuff:

$("#iframe").load(function() {
    var $this = $(this);
    var contents = $this.contents();

    contents.find('#droppable').droppable({
        drop: function (event, ui) { alert('dropped'); }
    });
    $('#draggables img').draggable();
});

The draggables become draggable and the droppable is successfully a drop target. The problem is that the landing zone for the drop area is not where it is displayed on the screen. That is, the alert is fired when the draggable is dropped somewhere above the drop target, and not on the target itself.

A few tests I did suggest that the difference between where the target is on screen and where jQuery thinks it is is related to the vertical position of the iframe on the page, but I can't find a direct correlation. Does anyone know whether this problem has been investigated by anyone anywhere and, perchance, solved?

Failing that, can anyone suggest a way I may be able to load an external HTML file into my page without using an iframe and without the two pages' structures and styles interfering with one another? I'm considering loading the inner page directly and using javascript to draw page controls around it.

TIA Altreus

回答1:

You're trying to access the parent element from within the child iframe. I haven't personally tested it, but try to set context for your jquery selector. Otherwise, it'll look only inside the current iFrame.

$('#draggables img', parent).draggable();


回答2:

It was asked a long ago, but digging SO I found a GIST where people solved this problem by overwriting the default behavior of $.ui.ddmanager.prepareOffsets.

You can find the working code here: https://gist.github.com/gujiman/581a3cee1dbf4beafccb