disable text drag and drop

前端 未结 7 1855
后悔当初
后悔当初 2020-12-08 16:14

There is a common feature of modern browsers where a user can select some text and drag it to an input field. Within the same field it causes moving of text, between differe

7条回答
  •  悲哀的现实
    2020-12-08 17:00

    This code will work in all versions of Mozilla and IE.

    function preventDrag(event)
    {
     if(event.type=='dragenter' || event.type=='dragover' || //if drag over event -- allows for drop event to be captured, in case default for this is to not allow drag over target
        event.type=='drop') //prevent text dragging -- IE and new Mozilla (like Firefox 3.5+)
     {
      if(event.stopPropagation) //(Mozilla)
      {
       event.preventDefault();
       event.stopPropagation(); //prevent drag operation from bubbling up and causing text to be modified on old Mozilla (before Firefox 3.5, which doesn't have drop event -- this avoids having to capture old dragdrop event)
      }
      return false; //(IE)
     }
    }
    
    //attach event listeners after page has loaded
    window.onload=function()
    {
     var myTextInput = document.getElementById('textInput'); //target any DOM element here
    
     if(myTextInput.addEventListener) //(Mozilla)
     {
      myTextInput.addEventListener('dragenter', handleEvents, true); //precursor for drop event
      myTextInput.addEventListener('dragover', handleEvents, true); //precursor for drop event
      myTextInput.addEventListener('drop', preventDrag, true);
     }
     else if (myTextInput.attachEvent) //(IE)
     {
      myTextInput.attachEvent('ondragenter', preventDrag);
      myTextInput.attachEvent('ondragover', preventDrag);
      myTextInput.attachEvent('ondrop', preventDrag);
     }
    }
    

提交回复
热议问题