Drag'n'drop dataTransfer.getData empty

后端 未结 2 1099
长发绾君心
长发绾君心 2021-01-11 16:43

I\'m trying to get drag\'n\'drop to work, but I seem to be completely missing how the getData/setData works.

I\'m using this code (http://jsfiddle.net/ASKte/218/)

相关标签:
2条回答
  • 2021-01-11 17:20

    If you really need to access data in other drop-events, use dataTransfer.types. Use JSON.parse, JSON.stringify and encode/decode uppercase characters to get around dataTransfer.types getting lower cased.

    Setting data:

    event.dataTransfer.setData(encodeUpperCase(JSON.stringify(value)), '');
    

    Getting data:

    const data = JSON.parse(decodeUpperCase(event.dataTransfer.types[0]))
    

    Where the encoding/decoding goes something like this:

      const UPPERCASE_PREFIX = '^{';
      const UPPERCASE_SUFFIX = '}^';
    
      function encodeUpperCase(str: string): string {
        return str.replace(/([A-Z]+)/g, `${UPPERCASE_PREFIX}$1${UPPERCASE_SUFFIX}`);
      }
    
      function decodeUpperCase(str: string): string {
        const escapeRegExp = (escape: string) => ['', ...escape.split('')].join('\\');
    
        return str.replace(
          new RegExp(`${escapeRegExp(UPPERCASE_PREFIX)}(.*?)${escapeRegExp(UPPERCASE_SUFFIX)}`, 'g'),
          (_, p1: string) => p1.toUpperCase()
        );
      }
    

    It works, but you might summon Cthulhu in the process.

    0 讨论(0)
  • 2021-01-11 17:29

    The data is only available on drop, this is a security feature since a website could grab data when you happen to be dragging something across the webpage.

    var el = angular.element(document.getElementById('drag'));
    el.attr("draggable", "true");
    el.bind("dragstart", function(e) {
        e.dataTransfer.setData('text', 'Where have you gone?!?!')         
    });
    
    var target = angular.element(document.getElementById('drop'));
    target.bind("dragover", function(e) {
        if (e.preventDefault) {
            e.preventDefault(); // Necessary. Allows us to drop.
        }
        return false;
    });
    
    target.bind("drop", function(e) {
        console.debug(e.dataTransfer.types);
        console.debug(e.dataTransfer.getData('text'));
    });  
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div id="drag" style="width: 100px; height: 100px; background-color: blue;"></div>
    
    <div id="drop" style="width: 100px; height: 100px; background-color: green;"></div>

    0 讨论(0)
提交回复
热议问题