将进入/退出事件限制为仅d3.js中的背景div

时间:2019-05-13 14:07:13

标签: javascript d3.js

当光标在包含SVG的特定DIV上移动时,我想显示带有坐标的移动十字线。

> git clone https://github.com/codeforequity-at/botium-cli.git && git checkout bugfix/-BOT-584-core-botium-cli-dialogflow-impor 上,我可以成功创建一个显示坐标的mouseenter(并在rect上将其删除),但是,将光标移到新创建的mouseout或文本上本身会触发rect mouseout事件周期。

我在多个地方都尝试过mouseenter,但似乎都没有用。

图片显示了如果您小心地将鼠标移到灰色的“屏幕”上,将创建矩形和文本并将其保留在一个位置。

但是,如果您移动光标以触摸“ bobo”或绿色矩形,它将开始移动。

enter image description here

d3.event.stopPropagation()

该代码尚未实现移动。首先,我只想在var infoBox = null; var theSVG = d3.select("#theScreen") .append("svg") .attr("width", 250) .attr("height", 250); // Register mouse events theSVG .on("mouseenter", mouseEnter) .on("mouseout", mouseExit); function mouseEnter() { if (infoBox !== null) return; var coord = d3.mouse(d3.event.currentTarget); x1 = parseInt(coord[0]); y1 = parseInt(coord[1]); console.log("mouseEnter", x1, y1, infoBox); infoBox = theSVG.append("g") .attr('class', 'ssInfoBox'); var rectItem = infoBox.append("rect") .attr('x', x1) .attr('y', y1) .attr('width', 30) .attr('height', 20); var textItem = infoBox.append("text") .attr('x', x1) .attr('y', y1) .text("bobo"); } function mouseExit() { if (infoBox === null) return; console.log("mouseExit", infoBox); infoBox.remove() infoBox = null; } mouseenter上创建和销毁矩形/文本。

我该怎么做?

Link to Fiddle.

2 个答案:

答案 0 :(得分:0)

您可以在div顶部以相同的大小创建透明的svg或任何其他标签。比处理此叠加层的鼠标事件。 这样,您就不会被内部组件事件打断。 缺点-您将不得不手动处理与内部构件的交互。

像这样:

<svg style="z-index:1;position:absolute;left:0;width:200px;top:0;height:200px">...</svg>

<div id="overlay" style="background:rgba(0,0,0,0);z-index:2;position:absolute;left:0;width:200px;top:0;height:200px"></div>

答案 1 :(得分:0)

使用[Authorize]代替mouseout

MDN对它们之间的区别有很好的解释:https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseleave_event

这是您的代码,只有该更改:

mouseleave
var infoBox = null;

var theSVG = d3.select("#theScreen")
  .append("svg")
  .attr("width", 250)
  .attr("height", 250);

// Register mouse events
theSVG
  .on("mouseenter", mouseEnter)
  .on("mouseleave", mouseExit);

function mouseEnter() {
  if (infoBox !== null)
    return;

  var coord = d3.mouse(d3.event.currentTarget);
  x1 = parseInt(coord[0]);
  y1 = parseInt(coord[1]);

  console.log("mouseEnter", x1, y1, infoBox);

  infoBox = theSVG.append("g")
    .attr('class', 'ssInfoBox');

  var rectItem = infoBox.append("rect")
    .attr('x', x1)
    .attr('y', y1)
    .attr('width', 30)
    .attr('height', 20);

  var textItem = infoBox.append("text")
    .attr('x', x1)
    .attr('y', y1)
    .text("bobo");
}

function mouseExit() {
  if (infoBox === null)
    return;

  console.log("mouseExit", infoBox);
  infoBox.remove()
  infoBox = null;
}
#container {
  width: 400px;
  height: 400px;
  background-color: #0BB;
}

#theScreen {
  position: absolute;
  top: 50px;
  left: 50px;
  width: 250px;
  height: 250px;
  background-color: #333;
  cursor: crosshair;
}

.ssInfoBox rect {
  fill: #383;
}

.ssInfoBox text {
  fill: white;
}