如何使嵌套元素在可拖动容器中不可拖动? [英] How can I make a nested element not draggable in a draggable container?

查看:48
本文介绍了如何使嵌套元素在可拖动容器中不可拖动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using HTML5 drag and drop on a parent container, but I want to disable the drag effect on some of its children, specifically an input so that users can select/edit input content easily.

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

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

默认情况下,Safari似乎会对输入内容执行此操作,因此请在Chrome或Firefox上尝试使用它.

Safari seems to do this for inputs by default so try it on Chrome or Firefox.

推荐答案

我正在寻找类似的东西,并使用mousedown和mouseup事件找到了可能的解决方案.这不是最优雅的解决方案,但它是唯一一个在chrome和firefox上对我来说始终如一的解决方案.

I was looking for something similar and found a possible solution using the mousedown and mouseup events. It's not the most elegant solution but it's the only one that worked consistently for me on both chrome and firefox.

我在您的小提琴中添加了一些JavaScript:小提琴

I added some javascript to your fiddle: Fiddle

;
(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));

这篇关于如何使嵌套元素在可拖动容器中不可拖动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆