【问题标题】:Unable to listen to dragend event on div无法收听 div 上的 dragend 事件
【发布时间】:2022-01-07 11:17:56
【问题描述】:

我有一个div,我只想在其中收听dragend 事件,但由于某种原因,它不起作用。当蓝色框落入矩形内但它什么也没提供时,我想控制台日志...

代码如下:

<!DOCTYPE html>
<html>
  <head>
    <style>
      #a {
        width: 350px;
        height: 70px;
        padding: 10px;
        border: 1px solid #aaaaaa; }
      #drag1 {
        background-color: blue;
        width: 100px;
        height: 70px;
      }
    </style>
  </head>

  <body>
    <p>Drag the blue box into the rectangle and wait for the console log:</p>

    <div id="a"></div>
    <br />
    <div id="drag1" draggable="true"></div>
  </body>

  <script>
    dropArea = document.getElementById("a");
    dragger = document.getElementById("drag1");
    dropArea.addEventListener("dragend", () => {
      console.log("Hello.....");
    });
  </script>
</html>

【问题讨论】:

    标签: javascript draggable


    【解决方案1】:

    dragend 事件在您完成拖动时从元素拖动中启动

    你必须将 dragend 事件放在拖动元素而不是放置区域

    改变

    dropArea.addEventListener("dragend", () => {
    

    通过

    dragger.addEventListener("dragend", () => {
    

        dropArea = document.getElementById("a");
        dragger = document.getElementById("drag1");
        dragger.addEventListener("dragend", () => {
          console.log("Here.....");
        });
    <!DOCTYPE html>
    <html>
      <head>
        <style>
          #a {
            width: 350px;
            height: 70px;
            padding: 10px;
            border: 1px solid #aaaaaa; }
          #drag1 {
            background-color: blue;
            width: 100px;
            height: 70px;
          }
        </style>
      </head>
    
      <body>
        <p>Drag the blue box into the rectangle and wait for the console log:</p>
    
        <div id="a"></div>
        <br />
        <div id="drag1" draggable="true"></div>
      </body>
    
    </html>

    【讨论】:

    • 啊,谢谢!但问题是我只想console.log() 只有当项目是dragend 时才在那个矩形上。目前,它在dragend 的任何地方都会吐出“你好……”
    • 好的,我明白了。我们可以做if element classname == my target classname 谢谢!
    • 恭喜您取得成功 ;) 使用元素类名是执行所需操作的好方法
    猜你喜欢
    • 1970-01-01
    • 2023-04-08
    • 2022-01-04
    • 1970-01-01
    • 2021-12-25
    • 2020-11-04
    • 1970-01-01
    • 2013-10-10
    • 1970-01-01
    相关资源
    最近更新 更多