How do I prevent drag on a child, but allow drag on the parent?(如何防止拖累孩子,但允许拖累父母?)
问题描述
我有一个用户可以拖动的 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.
推荐答案
如果你想真正取消拖动并使其不被父拖动处理程序注意到,你需要同时 preventDefault
和 stopPropagation
:
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.
这篇关于如何防止拖累孩子,但允许拖累父母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何防止拖累孩子,但允许拖累父母?


- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01