如何防止拖累孩子,但允许拖累父母? [英] How do I prevent drag on a child, but allow drag on the parent?

查看:16
本文介绍了如何防止拖累孩子,但允许拖累父母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户可以拖动的 div,在该 div 内是一个跨度,其中包含一些我希望允许用户选择的文本(因此他们不能拖动它).如何允许 div 拖动,但不允许 span?

I have a div which the user can drag, inside that div is a span with some text which I want to allow the user to select (thus they cannot drag it). How do I allow the div to drag, but not the span?

dragstart 事件在 div 上.

The dragstart event is on the div.

我可能忽略了一些简单的事情.我在 div 上尝试了 draggable=true,在跨度上尝试了 draggable=false.那没有用.尝试在 dragstart 上返回 false,但也没有用.

I'm probably overlooking something simple. I tried draggable=true on the div, and draggable=false on the span. That didn't work. Tried returning false on dragstart, that didn't work either.

dragstart(大致):

dragstart (roughly):

var jTarget = $(e.target);
if ((jTarget.is('div.header') || (jTarget.parents('div.header')) 
       && !jTarget.is('a, input, span'))) 
{
   e.originalEvent.dataTransfer.setData("Text", "test");
}
else
{
   if(e.preventBubble)
      e.preventBubble();
   if(e.stopPropagation)
      e.stopPropagation();
   return false;//???
}

if else 部分按我的预期工作,但我无法停止拖动并允许选择.

The if else portion works as I expect, but I cannot get anything to stop the drag and allow the select.

推荐答案

如果你想真正取消拖动并使其不被父拖动处理程序注意到,你需要同时 preventDefaultstopPropagation:

If you want to truly cancel out the drag and make it unnoticeable to parent drag handlers, you need to both preventDefault and stopPropagation:

<div draggable="true" ondragstart="console.log('dragging')">
    <span>Drag me! :)</span>
    <input draggable="true"
           ondragstart="event.preventDefault();
                        event.stopPropagation();"
           value="Don't drag me :(">
</div>

没有stopPropagation,即使默认行为被阻止(event.defaultPrevented == true),父级ondragstart仍然会被调用).如果您在该处理程序中有不处理这种情况的代码,您可能会看到一些细微的错误.

Without the stopPropagation, the parent ondragstart will still be called even if the default behavior will be prevented (event.defaultPrevented == true). If you have code in that handler that doesn't handle this case, you may see subtle bugs.

当然你也可以把上面的 JavaScript 放到 element.addEventListener('dragstart', ...) 里面.

You can of course put the JavaScript above inside element.addEventListener('dragstart', ...) too.

这篇关于如何防止拖累孩子,但允许拖累父母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆