拖放< span>到段落使用jQuery [英] Drag and drop <span> to paragraph using JQuery

查看:102
本文介绍了拖放< span>到段落使用jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将<span>拖放到<p>.我的代码可以用,但是我有3个问题,

I need to drag and drop <span> to <p>. My code works, but I have 3 problems,

  1. 当我通过键入某些内容(假设三个单词)来编辑<p>内容时,将<span>拖动到<p>之后,新键入的单词将作为一个单词.因此,不能在这些新键入的内容之间放置可拖动组件.

  1. When I edit <p> content by typing something(suppose three words) and after drag <span> to <p> newly typed words acting as one word. So cannot drop draggable components between those newly typed content.

关闭后,添加的可拖动组件(通过单击X)在两个单词之间保留两个空格.

After the close, the added draggable components(by clicking X) two spaces are remaining between two words.

不能将可拖动组件作为段落的第一个单词.

Cannot drop the draggable component as the 1 word of the paragraph.

为弄清第3个问题,我在该段的第1个中添加了&nbsp;.并进行排序.

To sort out the 3rd issue I added &nbsp; to the 1st of the paragraph. and it's sorted.

<p class="given" contenteditable="true">&nbsp; Lorem Ipsum is simply dummy</p>

如何解决其他两个问题?请帮助

How can I sort out the other two issues? Please help

$(function() {
  function textWrapper(str, sp) {
    if (sp == undefined) {
      sp = [0, 0];
    }
    var txt = "<span class='w'>" + str + "</span>";
    
    if (sp[0]) {
      txt = "&nbsp;" + txt;
    }
    
    if (sp[1]) {
      txt = txt + "&nbsp;";
    }
    
    return txt;
  }

  function chunkWords(p) {
    var words = p.split(" ");
    words[0] = textWrapper(words[0], [0, 1]);
    var i;
    for (i = 1; i < words.length; i++) {
      if (words[0].indexOf(".")) {
        words[i] = textWrapper(words[i], [1, 0]);
      } else {
        words[i] = textWrapper(words[i], [1, 1]);
      }
    }
    return words.join("");
  }

  function makeBtn(tObj) {
    var btn = $("<span>", {
      class: "ui-icon ui-icon-close"
    }).appendTo(tObj);
    btn.click(function(e) {
      $(this).parent().remove();
    });
  }

  function makeDropText(obj) {
    return obj.droppable({
      drop: function(e, ui) {
        var txt = ui.draggable.text();
        var newSpan = textWrapper(txt, [1, 0]);
        $(this).after(newSpan);
        makeBtn($(this).next("span.w"));
        makeDropText($(this).next("span.w"));
        $("span.w.ui-state-highlight").removeClass("ui-state-highlight");
      },
      over: function(e, ui) {
        $(this).add($(this).next("span.w")).addClass("ui-state-highlight");
      },
      out: function() {
        $(this).add($(this).next("span.w")).removeClass("ui-state-highlight");
      }
    });
  }

  $("p.given").html(chunkWords($("p.given").text()));

  $("span.given").draggable({
    helper: "clone",
    revert: "invalid"
  });

  makeDropText($("p.given span.w"));
});

p.given {
  display: flex;
  flex-wrap: wrap;
}

p.given span.w span.ui-icon {
  cursor: pointer;
}

div.blanks {
  display: inline-block;
  min-width: 50px;
  border-bottom: 2px solid #000000;
  color: #000000;
}

div.blanks.ui-droppable-active {
  min-height: 20px;
}

span.answers>b {
  border-bottom: 2px solid #000000;
}

span.given {
  margin: 5px;
}

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="row">
  <p class="given" contenteditable="true">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
</div>

<div class="divider"></div>
<div class="section">
  <section>
    <div class="card blue-grey ">
      <div class="card-content white-text">
        <div class="row">
          <div id="walkinDiv" class="col s12">
            <span class="given btn-flat white-text red lighten-1" rel="1">the Santee, thDakota</span>
            <span class="given btn-flat white-text red lighten-1" rel="2">America</span>
            <span class="given btn-flat white-text red lighten-1" rel="3">Qatar</span>
            <span class="given btn-flat white-text red lighten-1" rel="4">Philippines</span>
          </div>
        </div>
      </div>
    </div>
  </section>
</div>

更新时间:2019-10-22

我更新了问题,因为从代码生成可拖动组件<span>时遇到了问题.我生成了可拖动的组件,如下所示,它可以很好地拖放到<p>.但是当我单击<p>并从<p>(在发生模糊事件时)单击外部时,放置的组件未显示关闭按钮.它显示为[Ameriaca] , [Qatatr]为什么会这样?我该如何避免.我在$(function() {});

I updated the question because I faced a problem when I generate draggable components <span> from code. I generated draggable components as follows, Its generate fine and able drag and drop to <p>. but when I click the <p> and click outside from the <p>(which means in the blur event) dropped component not showing the close button. it showing as [Ameriaca] , [Qatatr] Why it happen so? how can I avoid it. I called this GetAllParameters() inside $(function() {});

function GetAllParameters() {
    $.ajax({
        type: "POST",
        url: SERVER_PATH + '/service/TestService.asmx/GetAllParameters',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: GetAllNotificationParametersComplete,
        error: GetAllNotificationParameterFailed
    });
}

function GetAllNotificationParametersComplete(result, status) {
    NotificationParameters = JSON.parse(result.d);
    getTemplateparameters(NotificationParameters,'ShowIn');
}

function GetAllNotificationParameterFailed(result) {
    //console.log(result);
}


function getTemplateparameters(data,field) {

    var filtered = data.filter(function(item) {
         return item[field] == true;
    });
 populateTemplateParameters(filtered);
}

function populateTemplateParameters(data) {  
     var obj = data;
     var stringlist = "";
     $.each(obj, function (index, item) {
         stringlist = stringlist + ' <span class="given btn-flat white-text red lighten-1 parameter-wrapper">' +item.ParameterName+ '</span>';
     });
    $("#walkinDiv").html(stringlist);

    $("span.given").draggable({
      helper: "clone",
      revert: "invalid"
    });

  makeDropText($("p.given span.w"));
}

更新时间:2019-10-23

当可拖动组件具有两个词(例如,"Hello World")并且我识别出一件事时,就会发生前面提到的问题.当我在可编辑的<p>中键入内容并单击<p>的外部时,键入了删除的单词.这是一个大问题.请帮我解决这个问题

The previously mentioned problem occurs when the draggable component has two words such as "Hello World" And one thing I Identified. When I typing something Inside editable <p> and click the outside of the <p> typed words removing.this is a big issue. please help me to solve this

推荐答案

您仅应根据自己遇到的实际问题提出实用,可回答的问题.闲话,开放式问题削弱了我们网站的实用性,并将其他问题从首页上推开.

You should only ask practical, answerable questions based on actual problems that you face. Chatty, open-ended questions diminish the usefulness of our site and push other questions off the front page.

您的问题应在合理范围内.如果您能想象整本书都能回答您的问题,那么您提出的要求就太多了.

Your questions should be reasonably scoped. If you can imagine an entire book that answers your question, you’re asking too much.

$(function() {
  function textWrapper(str, sp, btn) {
    if (sp == undefined) {
      sp = [0, 0];
    }
    var txt = "";
    if (btn) {
      txt = "<span class='w b'>" + str + "</span>";
    } else {
      txt = "<span class='w'>" + str + "</span>";
    }

    if (sp[0]) {
      txt = "&nbsp;" + txt;
    }

    if (sp[1]) {
      txt = txt + "&nbsp;";
    }

    return txt;
  }

  function chunkWords(p) {
    var words = p.split(" ");
    words[0] = textWrapper(words[0], [0, 1]);
    var i;
    for (i = 1; i < words.length; i++) {
      var re = /\[.+\]/;
      if (re.test(words[i])) {
        var b = makeTextBox(words[i].slice(1, -1));
        words[i] = "&nbsp;" + b.prop("outerHTML") + "&nbsp;";
      } else {
        if (words[0].indexOf(".")) {
          words[i] = textWrapper(words[i], [1, 0]);
        } else {
          words[i] = textWrapper(words[i], [1, 1]);
        }
      }
    }
    return words.join("");
  }

  function unChunkWords(tObj) {
    var words = [];
    $(".w", tObj).each(function(i, el) {
      console.log($(el).text(), $(el).attr("class"));
      if ($(el).hasClass("b")) {
        words.push("[" + $(el).text().trim() + "]");
      } else {
        words.push($(el).text().trim());
      }
    });
    return words.join(" ");
  }

  function makeBtn(tObj) {
    var btn = $("<span>", {
      class: "ui-icon ui-icon-close"
    }).appendTo(tObj);
  }

  function makeTextBox(txt) {
    var sp = $("<span>", {
      class: "w b"
    }).html(txt);
    makeBtn(sp);
    return sp;
  }

  function makeDropText(obj) {
    return obj.droppable({
      drop: function(e, ui) {
        var txt = ui.draggable.text();
        var newSpan = textWrapper(txt, [1, 0], 1);
        $(this).after(newSpan);
        makeBtn($(this).next("span.w"));
        makeDropText($(this).next("span.w"));
        $("span.w.ui-state-highlight").removeClass("ui-state-highlight");
      },
      over: function(e, ui) {
        $(this).add($(this).next("span.w")).addClass("ui-state-highlight");
      },
      out: function() {
        $(this).add($(this).next("span.w")).removeClass("ui-state-highlight");
      }
    });
  }

  $("p.given").html(chunkWords($("p.given").text()));

  $("p.given").on("click", ".b > .ui-icon", function() {
    $(this).parent().remove();
  });

  $("p.given").blur(function() {
    var w = unChunkWords($(this));
    console.log(w);
    $(this).html(chunkWords(w));
    makeDropText($("p.given span.w"));
  });

  $("span.given").draggable({
    helper: "clone",
    revert: "invalid"
  });

  makeDropText($("p.given span.w"));
});

p.given {
  display: flex;
  flex-wrap: wrap;
}

p.given span.w span.ui-icon {
  cursor: pointer;
}

div.blanks {
  display: inline-block;
  min-width: 50px;
  border-bottom: 2px solid #000000;
  color: #000000;
}

div.blanks.ui-droppable-active {
  min-height: 20px;
}

span.answers>b {
  border-bottom: 2px solid #000000;
}

span.given {
  margin: 5px;
}

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="row">
  <p class="given" contenteditable="true">Lorem Ipsum is simply dummy text of the printing and typesetting industry. [Lorem] Ipsum has been the industry's standard dummy text ever since the 1500s, Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
</div>

<div class="divider"></div>
<div class="section">
  <section>
    <div class="card blue-grey ">
      <div class="card-content white-text">
        <div class="row">
          <div class="col s12">
            <span class="given btn-flat white-text red lighten-1" rel="1">the Santee, thDakota</span>
            <span class="given btn-flat white-text red lighten-1" rel="2">America</span>
            <span class="given btn-flat white-text red lighten-1" rel="3">Qatar</span>
            <span class="given btn-flat white-text red lighten-1" rel="4">Philippines</span>
          </div>
        </div>
      </div>
    </div>
  </section>
</div>

使用blur事件,我们可以将包装的元素还原回文本,然后使用新内容再次将其分块.为了维护按钮,我使用了[].

Using the blur event, we can can revert the wrapped elements back into text and then chunk them back up again with the new content. To maintain the buttons, I used [ and ].

出于特定原因,我使用了.on().blur().

I used .on() and .blur() for specific reasons.

.on()方法将事件处理程序附加到jQuery对象中当前选定的元素集.从jQuery 1.7开始,.on()方法提供了附加事件处理程序所需的所有功能.

The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers.

委派的事件处理程序具有的优势是,它们可以处理来自后代元素的事件,这些事件在以后的时间添加到文档中.通过选择保证在附加委托事件处理程序时会出现的元素,您可以使用委托事件处理程序来避免频繁附加和删除事件处理程序的需要.例如,此元素可以是Model-View-Controller设计中视图的容器元素,如果事件处理程序希望监视document中的所有冒泡事件,则该元素可以为document.加载其他HTML之前,文档head中的document元素可用,因此可以在不等待文档准备就绪的情况下在其中附加事件.

Delegated event handlers have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated event handlers to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

查看更多: .on()

这很重要,因为我们正在动态创建元素,并希望确保将回调委派给这些元素,即使它们尚不存在.

This is important as we're dynamically creating elements and want to ensure the callback is delegated to these elements even if they do not exist yet.

此方法是.on( "blur", handler )

当模糊事件失去焦点时,它会发送到该元素.最初,此事件仅适用于表单元素,例如<input>.在最近的浏览器中,事件的域已扩展为包括所有元素类型.元素可以通过键盘命令(例如Tab键)或单击页面其他位置的鼠标来失去焦点.

The blur event is sent to an element when it loses focus. Originally, this event was only applicable to form elements, such as <input>. In recent browsers, the domain of the event has been extended to include all element types. An element can lose focus via keyboard commands, such as the Tab key, or by mouse clicks elsewhere on the page.

查看更多: .blur()

这篇关于拖放&lt; span&gt;到段落使用jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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