d3js behavior.drag 阻止可编辑的内容?

d3js behavior.drag prevents editable content?

我有一个小的弹出式编辑器,用于 d3js 应用程序中的一些数据输入。由于此编辑器有时会覆盖页面的有趣区域,因此我使用 behavior.drag

使弹出窗口可拖动

效果很好...我现在可以拖动弹出窗口了。但是我不能再编辑内容了。

有人知道为什么这不起作用,该怎么办?

这是我的问题的一个小提琴:https://jsfiddle.net/ey73b557/41/。 这是代码中的拖动行为:

// defined the drag behavior
var editTaskdrag = d3.behavior.drag()
        .on("drag", function(d,i) {
          var d3EditTaskObject = d3.select(this);
          d3EditTaskObject.style("left", addPx(d3EditTaskObject.style("left"), d3.event.dx)); 
          d3EditTaskObject.style("top", addPx(d3EditTaskObject.style("top"), d3.event.dy)); 
        })
          ;

您可以编辑 *edit me 文本。单击蓝色按钮,将出现一个带有相同 *edit me* 文本的弹出窗口。但是,您不能编辑这个。两个元素都将 contenteditable 设置为 true。

单击和拖动之间存在冲突,这在D3代码中是众所周知的。

对于您的情况,最简单的解决方案(当然不是最优雅的解决方案)就是在您单击跨度时删除拖动行为:

.on("click", function(){
    popupEditor.on(".drag", null)
})

这里是你的代码有那个变化:

// this generates the 'editor' - used for both the static and the draggable version
function simpleEditor(d3Object) {
  d3Object.append("span")
    .text("content: ");
  d3Object.append("span")
    .text(" * edit me * ")
    .attr("contenteditable", "true")
    .style("border", "solid black 1pt")
    .style("background", "lightblue")
    .on("click", function() {
      popupEditor.on(".drag", null)
    })
    .on("mouseout", function() {
      popupEditor.call(editTaskdrag)
    })
}
// arithmetic on strings with px at the end: addPx("110px", 23) = "133px"
function addPx(s, d) {
  var number = parseInt(s, 10); // this really works even if the string is "120px"
  number += d;
  return number.toString() + "px";
}
// defined the drag behavior
var editTaskdrag = d3.behavior.drag()
  .on("drag", function(d, i) {
    var d3EditTaskObject = d3.select(this);
    d3EditTaskObject.style("left", addPx(d3EditTaskObject.style("left"), d3.event.dx));
    d3EditTaskObject.style("top", addPx(d3EditTaskObject.style("top"), d3.event.dy));
  });
// generate the static editor
simpleEditor(d3.select("#staticEditor"))
  // and now the draggable editor, hidden, but with drag behavior
var popupEditor = d3.select("#popupEditor");
simpleEditor(popupEditor);
popupEditor.attr("hidden", "true")
  .call(editTaskdrag);
// click this button to get the draggable popup. However, it is not editable anymore
d3.select("#button")
  .on("click", function() {
    d3.select("#popupEditor")
      .style("position", "fixed")
      .style("left", "30%")
      .style("top", "30%")
      .style("background", "grey")
      .style("padding", "1em")
      .style("box-shadow", "0.5em 0.5em lightgrey")
      .attr("hidden", null)
  })
#button {
  background-color: blue;
  color: white;
  border: solid black 1pt;
  padding: 0.2em;
  border-radius: 1em
}
<script src="https://d3js.org/d3.v3.min.js"></script>
<body>
  <p id="staticEditor">
  </p>
  <p id="popupEditor">
  </p>
  <p>
    <span id="button">
Click here to open the pop up editor
</span>
  </p>
</body>