Javascript ondrag, ondragstart, ondragend

后端 未结 5 1873
暗喜
暗喜 2020-12-09 05:14

I\'ve been trying to use ondrag() and some other functions on a div rendered dynamically on an HTML page.

None of these events

相关标签:
5条回答
  • 2020-12-09 05:43

    Have a look at this documentation: https://developer.mozilla.org/En/DragDrop/Drag_and_Drop

    Note: It does not work in every browser.

    If you want a cross-browser support use jQuery: http://jqueryui.com/demos/draggable/

    jQuery example:

    <div id="draggable" class="ui-widget-content">
        <p>Drag me around</p>
    </div>
    
    <script>
        $(function() {
            $( "#draggable" ).draggable({
                drag: function(event, ui) {}
            });
        });
    </script>
    

    Another example:

    <div id="toBeDragged" draggable="true">
      This text <strong>may</strong> be dragged.
    </div>
    
    <script>
    document.getElementById('toBeDragged').addEventListener('dragstart', function(event) {
        event.dataTransfer.setData('text/plain', 'This text may be dragged');
    });
    </script>
    
    0 讨论(0)
  • 2020-12-09 05:46

    An easy way to do this is with jQuery UI, make sure you use it after your dynamic div has been rendered.

    $(document).ready(function () {
        $('.my_draggable_elements').draggable({
            drag: function(){
              // do something
            }
        });
    });
    
    0 讨论(0)
  • 2020-12-09 06:00

    Is there content in the div? I don't think it's the element itself that gets dragged in this particular event.

    0 讨论(0)
  • 2020-12-09 06:05

    I haven't used drag myself much but I believe it's the drag "edit action" - eg selecting text and dragging it within a textbox/textarea.

    You may need to implement your own onmousedown() onmouseup() and onmousemove() handlers for the functionality I think you're after

    0 讨论(0)
  • 2020-12-09 06:07

    Short answer: <div>-s are not draggable by default, unlike <a>-s. You must add draggable=true:

    <div draggable=true ondragstart=...>HTML</div>
    

    Works on Firefox 75 like that.

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