How do you make text selectable on a jQuery draggable div?

前端 未结 2 1302
無奈伤痛
無奈伤痛 2020-12-29 20:23

I made a div draggable using jQuery. However, there is some text in that box, and I would still like to be able to copy and paste the text, but when I make an item draggable

相关标签:
2条回答
  • 2020-12-29 21:10

    It doesn't make sense to allow dragging AND selecting text on the same element. However, if you keep thinking it's necessary, two things come to my mind:

    Solution 1:

    You can add a "handler" that will be the only child receiving the mouse down/up events to drag the div. For instance:

    <div id="draggable">
      <div class="handler"></div>
      <div class="text">This is a selectable text</div>
    </div>
    

    And in your JavaScript code:

    var draggableDiv = $('#draggable');
    draggableDiv.draggable({
      handle: $('.text', draggableDiv)
    });
    

    Solution 2:

    You can disable the draggable thing when a user try to select text:

    <div id="draggable">
      <div class="text">This is a text</div>
    </div>
    

    And in your JavaScript code:

    var draggableDiv = $('#draggable').draggable();
    $('.text', draggableDiv).mousedown(function(ev) {
      draggableDiv.draggable('disable');
    }).mouseup(function(ev) {
      draggableDiv.draggable('enable');
    });
    

    When someone tries to select something in .text, the draggable process is disabled.

    The first solution is the proper one.

    0 讨论(0)
  • 2020-12-29 21:23

    Use the cancel option when making the element draggable.

    Prevents dragging from starting on specified elements.

    $('.selector').draggable({ cancel: '.text' }); 
    
    0 讨论(0)
提交回复
热议问题