如何实现dragenter

问题描述 投票:0回答:1

我正在 Storyline 工作,但想使用 JS 来使用 EVentListener 处理 Dragenter/dragleave 情况。 我决定尝试一些简单的事情,以确保我了解如何使用这些。

我创建了一个“testarea”矩形和一个要在其上拖动的对象, 然后为该矩形的容器以及其中的 svg 和路径元素创建变量:

testarea = document.querySelector("[data-acc-text = 'testarea']")
testareasvgobject = testarea.querySelector("svg")
testareagobject = testareasvgobject.querySelector("path")

然后我测试了几行代码。

testareasvgobject.addEventListener("mouseover", function(){ alert("Hello World!"); });  //this works

testarea.addEventListener("dragenter", function(){ alert("Goodbye World!"); }); //this doesn't work
    
testareasvgobject.addEventListener("dragenter", function(){ alert("Goodbye World!"); }); //this doesn't work

testareagobject.addEventListener("dragenter", function(){ alert("Goodbye World!"); }); //this doesn't work

正如你所看到的,我尝试监听dragenter 的所有三个元素,但没有成功。 由于“mouseover”事件侦听器有效,因此语法似乎是正确的。

由于我正在创建在 Storyline 创作平台中工作的 javascript,因此我无法直接访问 css 或 html,因此我必须仅使用 JS 来处理所有这些。

我错过了什么?

event-listener dragenter
1个回答
0
投票

这是 svg-whiz.com/svg/DragAndDropGroup 上演示的修改版本,它是一个简单的 Dragenter 实现,应该适用于所有主要浏览器。

<?xml version='1.0' standalone='no'?>
<style>body {height:100vh; user-select: none}</style>
<svg width='100%' height='100%' xmlns='http://www.w3.org/2000/svg'
   onmousedown='Grab(evt)'
   onmousemove='Drag(evt)'
   onmouseup='Drop(evt)'>
   
   <title>Drag And Drop</title>

   <desc>
      A nice little demo of drag-and-drop functionality in SVG,
      written by Doug Schepers on February 16, 2004 and modified by rafaelcastrocouto at 2025.
      Use or misuse this code however you wish.
   </desc>

   <script><![CDATA[
      var SVGInit = null;
      var SVGDocument = null;
      var SVGRoot = null;

      var TrueCoords = null;
      var GrabPoint = null;
      var BackDrop = null;
      var DragTarget = null;
      var DragEnterTarget = null;

      function Init(evt)
      {
         SVGInit = true;
         SVGDocument = evt.target.ownerDocument.querySelector('svg');
         
         SVGRoot = evt.target.ownerSVGElement;
         // these svg points hold x and y values...
         //    very handy, but they do not display on the screen (just so you know)
         TrueCoords = SVGRoot.createSVGPoint();
         GrabPoint = SVGRoot.createSVGPoint();

         // this will serve as the canvas over which items are dragged.
         //    having the drag events occur on the mousemove over a backdrop
         //    (instead of the dragged element) prevents the dragged element
         //    from being inadvertantly dropped when the mouse is moved rapidly
         BackDrop = SVGDocument.getElementById('BackDrop');
      }

      function Grab(evt)
      {
         if (!SVGInit) Init(evt);
        
         // find out which element we moused down on
         var targetElement = evt.target;

         // you cannot drag the background itself, so ignore any attempts to mouse down on it
         if ( BackDrop != targetElement )
         {
            //set the item moused down on as the element to be dragged
            DragTarget = targetElement;
            if ( 'g' == DragTarget.parentNode.localName )
            {
               DragTarget = DragTarget.parentNode;
            }


            // move this element to the "top" of the display, so it is (almost)
            //    always over other elements (exception: in this case, elements that are
            //    "in the folder" (children of the folder group) with only maintain
            //    hierarchy within that group
            DragTarget.parentNode.appendChild( DragTarget );

            // turn off all pointer events to the dragged element, this does 2 things:
            //    1) allows us to drag text elements without selecting the text
            //    2) allows us to find out where the dragged element is dropped (see Drop)
            DragTarget.setAttributeNS(null, 'pointer-events', 'none');

            // we need to find the current position and translation of the grabbed element,
            //    so that we only apply the differential between the current location
            //    and the new location
            var transMatrix = DragTarget.getCTM();
            GrabPoint.x = TrueCoords.x - Number(transMatrix.e);
            GrabPoint.y = TrueCoords.y - Number(transMatrix.f);

         }
      };


      function Drag(evt)
      {
         if (!SVGInit) Init(evt);
        
         // account for zooming and panning
         GetTrueCoords(evt);

         // if we don't currently have an element in tow, don't do anything
         if (DragTarget)
         {
            // account for the offset between the element's origin and the
            //    exact place we grabbed it... this way, the drag will look more natural
            var newX = TrueCoords.x - GrabPoint.x;
            var newY = TrueCoords.y - GrabPoint.y;

            // apply a new tranform translation to the dragged element, to display
            //    it in its new location
            DragTarget.setAttributeNS(null, 'transform', 'translate(' + newX + ',' + newY + ')');
            
            // if collision DragEnter(evt);
            var targetElement = evt.target;
            if (DragTarget !== targetElement && BackDrop != targetElement ) {
              DragEnter(evt);
            }
         }
      };
      
      
      function DragEnter(evt)
      {
        
        if (DragEnterTarget !== evt.target) 
        {
          
          DragEnterTarget = evt.target;
          console.log(DragTarget.id + ' has been dragged on top of ' + DragEnterTarget.id);
          
        }
      }


      function Drop(evt)
      {
         if (!SVGInit) Init(evt);
        
         // if we aren't currently dragging an element, don't do anything
         if ( DragTarget )
         {
            // since the element currently being dragged has its pointer-events turned off,
            //    we are afforded the opportunity to find out the element it's being dropped on
            var targetElement = evt.target;

            // turn the pointer-events back on, so we can grab this item later
            DragTarget.setAttributeNS(null, 'pointer-events', 'all');
            if ( DragTarget != targetElement.parentNode )
            {
               if ( 'Folder' == targetElement.parentNode.id )
               {
                  // if the dragged element is dropped on an element that is a child
                  //    of the folder group, it is inserted as a child of that group
                  targetElement.parentNode.appendChild( DragTarget );
                  console.log(DragTarget.id + ' has been dropped into a folder, and has been inserted as a child of the containing group.');
               }
               else
               {
                  // for this example, you cannot drag an item out of the folder once it's in there;
                  //    however, you could just as easily do so here
                  console.log(DragTarget.id + ' has been dropped on top of ' + targetElement.id);
               }
            }

            // set the global variable to null, so nothing will be dragged until we
            //    grab the next element
            DragTarget = null;
         }
      };


      function GetTrueCoords(evt)
      {
         // find the current zoom level and pan setting, and adjust the reported
         //    mouse position accordingly
         var newScale = SVGRoot.currentScale;
         var translation = SVGRoot.currentTranslate;
         TrueCoords.x = (evt.clientX - translation.x)/newScale;
         TrueCoords.y = (evt.clientY - translation.y)/newScale;
      };


   ]]></script>

   <rect id='BackDrop' x='-10%' y='-10%' width='110%' height='110%' fill='none' pointer-events='all' />

   <circle id='BlueCircle' cx='25' cy='25' r='20' fill='blue'/>
   <circle id='RedCircle' cx='125' cy='25' r='20' fill='red'/>
   <circle id='OrangeCircle' cx='225' cy='25' r='20' fill='orange'/>
   <text id='DraggableText' x='20' y='200' fill='red' font-size='18px' font-weight='bold'>Draggable Text</text>


   <rect id='GreenRectangle' x='50' y='70' width='100' height='100' fill='green'/>

   <g id='Folder'>
      <rect id='FolderRectangle' x='300' y='100' width='300' height='150' fill='tan' stroke='brown' stroke-width='3'/>
      <text id='DraggableText' x='450' y='175' font-size='15px' font-weight='bold' text-anchor='middle' baseline-shift='-33%'>Drop here to add to draggable group.</text>
   </g>

</svg>

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.