問題描述
我有一個用戶可以拖動的 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.
這篇關于如何防止拖累孩子,但允許拖累父母?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!