如何防止拖累孩子,但允许拖累父母?

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.

推荐答案

如果你想真正取消拖动并使其不被父拖动处理程序注意到,你需要同时 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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)