Draggable and Clickable input element using jquery

前端 未结 4 997
抹茶落季
抹茶落季 2021-01-06 17:44

I have an input element inside a draggable div. My code should do the following things:

  • When I drag my input element, entire draggable div should be dragged. (
相关标签:
4条回答
  • 2021-01-06 18:09

    Really old question but I have a slightly different solution, so answering here.

    Disable draggable for input element by setting cancel attribute in the draggable initialiser. I think in most situations it is a small compromise. But YMMV.

    $(".card").draggable({
         cancel: "input"
    });
    
    0 讨论(0)
  • 2021-01-06 18:12

    You could try adding the contenteditable attribute to your div:

    HTML

    <div contenteditable="true" class="draggable" >
        <input type="text" value="drag me!"/>
    </div>
    

    JQuery

    $(".draggable").draggable()
      .click(function() {
        $(this).draggable( {disabled: false});
    }).dblclick(function() {
        $(this).draggable({ disabled: true });
    });
    

    JSFiddle

    0 讨论(0)
  • 2021-01-06 18:23

    You could dispatch event, e.g:

    -DEMO-

    $(".draggable").draggable({
        start: function (event, ui) {
            $(this).data('preventBehaviour', true);
        }
    });
    $(".draggable :input").on('mousedown', function (e) {
        var mdown = document.createEvent("MouseEvents");
        mdown.initMouseEvent("mousedown", false, true, window, 0, e.screenX, e.screenY, e.clientX, e.clientY, true, false, false, true, 0, null);
        $(this).closest('.draggable')[0].dispatchEvent(mdown);
    }).on('click', function (e) {
        var $draggable = $(this).closest('.draggable');
        if ($draggable.data("preventBehaviour")) {
            e.preventDefault();
            $draggable.data("preventBehaviour", false)
        }
    });
    
    0 讨论(0)
  • 2021-01-06 18:28
    $('.draggable input').click(function() {
        $(this).focus();
    });
    

    The input field is now editable, and you can still drag the whole div from the input field. JSFiddle.

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