Firefox: Unable to Drag element child of <a> hyperlink

喜欢而已 提交于 2019-12-08 10:25:04

问题


Consider the following markup:

<a class="link" href="#">
    <sup draggable="true">Foo</sup> Bar
</a>

Now attach a dragstart event to the sup element:

$(document).ready(function () {
    $("sup").on('dragstart', function(e) {
        console.log('shikaka');
    });
});

This event will never fire. I've been researching and in Firefox, links are draggable by default, so I thought that this might work:

$(document).ready(function () {
    $(".link").on('dragstart', function(e) {
         e.preventDefault();
         e.stopPropagation;
         //event return false; does not work.
    });

    $("sup").on('dragstart', function(e) {
        console.log('shikaka');
    });
});

And, doing <a class="link" href="#" draggable="false"> did not work either.

I've even tried some "crazy" stuff like triggering the event to the child:

$(".link").on('dragstart', function (e) {
    e.preventDefault();
    e.stopPropagation;
    $(this).find('sup').trigger('dragstart');
});

There are some post around the internet that show that you can also disable the event by cancelling the mousedown event. Any of the above examples where tried with dragenter and mousedown and all had the same effect.

My question is, is there any way to "short circuit" the default event in firefox to make it trigger the child element's event instead? Or, is there any way to only prevent the parent event but still be able to drag the child element?.


回答1:


I've being testing it, and if you remove the href attribute from the <a> tag it should not be draggable anymore and the event should not fire, and if you like to make both elements draggable add to it the attribute draggable === true, and then the drag event will fire in the <a> and in the children.

I you still need the data of the href attribute in the in the <a> tag, you could add it as another attribute like data-href or similar.

You could try it in the snippet below.

document.getElementById('a').addEventListener('dragstart', function() {
  console.log('Dragging a link…');
});

document.getElementById('span').addEventListener('dragstart', function() {
  console.log('Dragging a span…');
});
<a id="a" draggable="true">
  <div id="span" draggable="true">and some more text</div>
</a>


来源:https://stackoverflow.com/questions/32121801/firefox-unable-to-drag-element-child-of-a-hyperlink

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!