【问题标题】:Ordering sentences with span elements?用 span 元素排序句子?
【发布时间】:2018-09-28 19:39:56
【问题描述】:

我真的试图找到答案,但没有任何答案。我希望能够重新排序句子,即拖放它们。但我也希望它们是可编辑的。哦,是的,最好没有 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>

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

【问题讨论】:

标签: javascript html draggable


【解决方案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

【讨论】:

  • 按住Control键可以移动元素。
【解决方案2】:

要使某些东西可拖放...(这可能会相当长,因此仅列出步骤,而不是代码,如果其他人有精力编写它,不会怪您再做一个答案)。)

Step 1.当鼠标/触摸向下时,div位置弹出到上z,并根据鼠标/触摸位置相对于窗口移动位置。

第 2 步。让所有潜在的放置位置在 mouseenter 或等效位置上监听(通常 javascript 在现有位置之间制作临时的 1 或 0 高度 div。)如果 mouseenters/等效,使它们处于活动状态。如果鼠标/触摸离开,使它们处于非活动状态。

步骤 3a。如果在潜在放置 div 处于活动状态时 mouseup/endtouch,请将其替换为 span。

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

(注意:到目前为止,相当多的移动浏览器还不支持拖动 javascript。几年后,这可能是更好的选择)

【讨论】:

    【解决方案3】:

    因此,即使可行,我提出上述问题的方式似乎也很复杂。

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

    我最终尝试使用 vue 做一些事情,原因是更容易保留数据对象以进行排序和编辑,并在需要时根据需要使用虚拟 dom 进行显示。谢谢大家的建议!

    【讨论】:

      猜你喜欢
      • 2011-11-10
      • 2012-12-26
      • 2010-10-11
      • 2021-08-12
      • 1970-01-01
      • 2019-09-01
      • 2017-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多