D3.js Как поместить ссылку href в прямоугольник и вывести текст рядом с ней?

Когда я работал в Twitter, я написал утилиту для вычисления размера большого объекта. Он учитывает различные модели памяти (32-разрядные, сжатые oops, 64-bit), padding, subclass padding, корректно работает с круговыми структурами данных и массивами. Вы можете просто скомпилировать этот .java-файл; он не имеет внешних зависимостей:

https://github.com/twitter/commons/blob/master/src/java/com/twitter/common/objectsize/ObjectSizeCalculator.java

0
задан GGX 16 January 2019 в 09:21
поделиться

1 ответ

Многие приветствуют GGX

Это не лучшее решение, но, если вы читаете логику. Каждый раз, когда нажимается строка, запускается функция Down. Синий сможет вводить рекурсивно, а серый - не из-за проверки, существует ли дочерний элемент и находится ли он в переходном состоянии (если ни один из них не существует, нажатие на панель ничего не делает, поскольку ничего не возвращает).

Поэтому просто добавьте новую строку ниже строки 78 сразу после объявления функции down (d, i)

if (!d.children) window.open('https://www.google.com/search?q='+d.name,'popUpWindow');

где https: // www .google.com / search? q = - это местоположение href, к которому вы ведете. Вы можете удалить popUpWindow, если не нужно.


Если вы хотите, чтобы весь код был вокруг него (честно добавили только эту строку под строкой 78):

d3.json("readme.json", function(error, root) {
  if (error) throw error;

  partition.nodes(root);
  x.domain([0, root.value]).nice();
  down(root, 0);
});

function down(d, i) {
  if (!d.children) window.open('https://www.google.com/search?q='+d.name,'popUpWindow');
  if (!d.children || this.__transition__) return;
  var end = duration + d.children.length * delay;

  // Mark any currently-displayed bars as exiting.
  var exit = svg.selectAll(".enter")
      .attr("class", "exit");

  // Entering nodes immediately obscure the clicked-on bar, so hide it.
  exit.selectAll("rect").filter(function(p) { return p === d; })
      .style("fill-opacity", 1e-6);

  // Enter the new bars for the clicked-on data.
  // Per above, entering bars are immediately visible.
  var enter = bar(d)
      .attr("transform", stack(i))
      .style("opacity", 1);

  // Have the text fade-in, even though the bars are visible.
  // Color the bars as parents; they will fade to children if appropriate.
  enter.select("text").style("fill-opacity", 1e-6);
  enter.select("rect").style("fill", color(true));

  // Update the x-scale domain.
  x.domain([0, d3.max(d.children, function(d) { return d.value; })]).nice();

  // Update the x-axis.
  svg.selectAll(".x.axis").transition()
      .duration(duration)
      .call(xAxis);

  // Transition entering bars to their new position.
  var enterTransition = enter.transition()
      .duration(duration)
      .delay(function(d, i) { return i * delay; })
      .attr("transform", function(d, i) { return "translate(0," + barHeight * i * 1.2 + ")"; });

  // Transition entering text.
  enterTransition.select("text")
      .style("fill-opacity", 1);

  // Transition entering rects to the new x-scale.
  enterTransition.select("rect")
      .attr("width", function(d) { return x(d.value); })
      .style("fill", function(d) { return color(!!d.children); });

  // Transition exiting bars to fade out.
  var exitTransition = exit.transition()
      .duration(duration)
      .style("opacity", 1e-6)
      .remove();

  // Transition exiting bars to the new x-scale.
  exitTransition.selectAll("rect")
      .attr("width", function(d) { return x(d.value); });

  // Rebind the current node to the background.
  svg.select(".background")
      .datum(d)
    .transition()
      .duration(end);

  d.index = i;
}
0
ответ дан PonderWind 16 January 2019 в 09:21
поделиться
Другие вопросы по тегам:

Похожие вопросы: