如何使嵌套元素在可拖动容器中不可拖动



我在父容器上使用HTML5拖放,但我想禁用其某些子容器的拖动效果,特别是输入,以便用户可以轻松选择/编辑输入内容。

例: https://jsfiddle.net/Luzub54b/

<div class="parent" draggable="true">
   <input class="child" type="text" value="22.99"/>
</div>

默认情况下,Safari似乎对输入执行此操作,因此请在Chrome或Firefox上尝试。

我正在寻找类似的东西,并使用鼠标按下和鼠标向上事件找到了可能的解决方案。这不是最优雅的解决方案,但它是唯一一个在chrome和Firefox上始终如一的解决方案。

我在你的小提琴中添加了一些javascript:小提琴

;
(function($) {
  // DOM Ready
  $(function() {
    $('input').on('mousedown', function(e) {
      e.stopPropagation();
      $('div.parent').attr('draggable', false);
    });
    $(window).on('mouseup', function(e) {
      $('div.parent').attr('draggable', true);
    });
    /**
     * Added the dragstart event handler cause 
     * firefox wouldn't show the effects otherwise
     **/
    $('div.parent').on({
      'dragstart': function(e) {
        e.stopPropagation();
        var dt = e.originalEvent.dataTransfer;
        if (dt) {
          dt.effectAllowed = 'move';
          dt.setData('text/html', '');
        }
      }
    });
  });
}(jQuery));

最新更新