用跨度元素对句子排序?

时间:2018-09-28 19:39:56

标签: javascript html draggable

我确实试图找到答案,但没有结果。我希望能够对句子进行重新排序,即拖放它们。但是我也希望它们是可编辑的。哦,是的,最好没有jquery之类的东西。

例如如果需要在编辑和重新排序之间切换,请使用“ ctr”键切换内容。但是我无法弄清楚拖动事件如何弄清楚放置它的位置。

<!DOCTYPE html>
<html>
<style>
.sentence1 {color: blue;}
.sentence2 {color: red;}
.sentence3 {color: green;}
</style>
<body>
<div class="paragraph">
<span id="three" class="sentence3" contenteditable="true" >This is really the third sentence.</span>
<span id="one" class="sentence1" contenteditable="true" >This is really the first sentence.</span> 
<span id="two" class="sentence2" contenteditable="true" >This is really the second sentence.</span> 
</div>

我认为这对某些人来说可能是有用的,如果解决的话,所以我没有提供更多我尝试过并失败的代码。任何建议最欢迎!

3 个答案:

答案 0 :(得分:1)

我准备了一个小沙箱供您随意使用。底部的小提琴链接。

var SPANs = document.getElementsByTagName("span");

document.body.addEventListener("keydown", function (event) {
    if (event.key === "Control") {
      Array.prototype.forEach.call(SPANs, function (item) {
      item.setAttribute("contenteditable", false);
    });
  }
});

document.body.addEventListener("keyup", function (event) {
  Array.prototype.forEach.call(SPANs, function (item) {
    item.setAttribute("contenteditable", true);
  });
});

Array.prototype.forEach.call(SPANs, function (item) {
  item.addEventListener("drag", function (event) {
    console.log("Moving element");
  }, false);
});

Fiddle with a little piece of JS code

答案 1 :(得分:0)

要使某些东西可拖放...(这可能会很长,因此仅列出步骤而不是代码,如果其他人有能力将其编写出来,则不会怪您提出其他答案

第1步:在鼠标/向下触摸时使div位置弹出到z,然后根据鼠标/触摸位置相对于窗口移动位置。

第2步。让所有可能的放置位置在mouseenter或等效位置上侦听(通常javascript在现有的位置之间临时设置1或0高度的div。)如果mouseenter /等效,请将其激活。如果鼠标/触摸离开,请使其变为非活动状态。

步骤3a。如果在可能的位置div处于活动状态时mouseup / endtouch,请将其替换为跨度。

步骤3b。如果在没有潜在的位置div处于活动状态的情况下mouseup / endtouch,请删除临时div,然后将拾取的div放回原来的位置。

(注意:拖动javascript尚不支持许多移动浏览器。几年后,这可能是更好的选择)

答案 2 :(得分:0)

因此,即使我可以将上面的问题框起来,这看起来也很复杂。

我认为使用sortable.js(不是jquery)是一种途径。

我最终尝试使用vue来做某事,原因是保留数据对象进行排序和编辑以及在需要时使用虚拟Dom进行显示比较容易。谢谢大家的建议!