简体   繁体   English

如何使所有 contenteditable 子元素可拖动?

[英]How to make all contenteditable child elements draggable?

I simply would like a function that allows all contenteditable child elements draggable using jQuery (no external jQuery plugins).我只是想要一个 function ,它允许使用 jQuery (没有外部 jQuery 插件)拖动所有 contenteditable 子元素。

I found this useful piece of code here How do I make an element draggable in jQuery?我在这里找到了这段有用的代码如何在 jQuery 中使元素可拖动? . .

    function draggable(e){
    window.my_dragging = {};
    my_dragging.pageX0 = e.pageX;
    my_dragging.pageY0 = e.pageY;
    my_dragging.elem = this;
    my_dragging.offset0 = $(this).offset();
    function handle_dragging(e){
        var left = my_dragging.offset0.left + (e.pageX - my_dragging.pageX0);
        var top = my_dragging.offset0.top + (e.pageY - my_dragging.pageY0);
        $(my_dragging.elem)
        .offset({top: top, left: left});
    }
    function handle_mouseup(e){
        $('body')
        .off('mousemove', handle_dragging)
        .off('mouseup', handle_mouseup);
    }
    $('body')
    .on('mouseup', handle_mouseup)
    .on('mousemove', handle_dragging);
}

This allows draggability on any element by simply typing $('.div').on("mousedown", draggable);只需键入$('.div').on("mousedown", draggable);就可以在任何元素上进行拖动。

I have also found this useful piece of code here Prevent contenteditable adding <div> on ENTER - Chrome .我还在这里找到了这段有用的代码防止 contenteditable 添加 <div> on ENTER - Chrome

    $('div[contenteditable]').keydown(function(e) {
    // catch the enter key being pressed
    if (e.keyCode === 13) {
      $(this).find("*").off("mousedown.drag").on("mousedown.drag", draggable);
    }
  });

i intend on attaching the function to all child elements the contenteditable creates when the user presses enter to make them draggable.我打算将 function 附加到 contenteditable 在用户按下回车键以使其可拖动时创建的所有子元素。

Can anybody help?有人可以帮忙吗?

I recommend using jQuery UI's draggable feature:我推荐使用 jQuery UI 的可拖动功能:

  <script>
      $(function() {
          $("div[contenteditable]").draggable();
      });
  </script>

It's very simple and if you want to avoid overloading your page with unused features of jQuery UI, you can deselect components in the jQuery UI download section to reduce it to your needs.它非常简单,如果您想避免使用 jQuery UI 的未使用功能使您的页面超载,您可以取消选择 jQuery UI 下载部分中的组件以减少它以满足您的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM