如何阻止drag事件冒泡?

新手上路,请多包涵

子元素会触发父元素的drag,如何阻止呢?求解!!!DOM 结构如下:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>drag</title>
  </head>
  <body>
    <div
      id="father"
      draggable="true"
      style="width: 200px; height: 200px; background: red"
    >
      <div
        draggable="false"
        id="child"
        style="width: 50px; height: 50px; background: blue"
      ></div>
    </div>

    <script>
      const father = document.querySelector("#father");
      const child = document.querySelector("#child");

      child.addEventListener("click", (e) => {
        console.log("child click");
        e.stopPropagation();
      });

      child.addEventListener("dragstart", (e) => {
        e.stopPropagation();
      });

      child.addEventListener("drag", (e) => {
        e.stopPropagation();
      });

      // =================

      father.addEventListener("click", (e) => {
        console.log("father click");
      });

      father.addEventListener("dragstart", (e) => {
        console.log("father dragstart");
      });

      father.addEventListener("drag", (e) => {
        console.log("father drag");
      });

      father.addEventListener("dragover", (e) => {
        // console.log("father dragover");
      });

      father.addEventListener("dragend", (e) => {
        console.log("father dragend");
      });
    </script>
  </body>
</html>
阅读 8k
2 个回答

设置子元素 draggable="true",然后还缺少dragend的阻止

child.addEventListener("dragend", (e) => {
   e.stopPropagation();
});

但是这样子元素也会有拖拽效果

drag.gif

可以通过设置拖拽预览图setDragImage为透明图就行了

child.addEventListener("dragstart", (e) => {
   e.stopPropagation();
   var img = new Image();
   img.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' %3E%3Cpath /%3E%3C/svg%3E"; // 透明图
   e.dataTransfer.setDragImage(img, 0, 0);
});

drag2.gif

这样看着子元素就不能拖拽了

新手上路,请多包涵
  1. 子元素 draggable = true
  2. 子元素 dragstart 回调中 stopPropagation(); preventDefault(); 即可阻止冒泡,并屏蔽资源 dragstart 默认行为
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏