在d3 SVG下拉菜单

时间:2015-11-14 05:23:09

标签: javascript html css d3.js svg

我被困住了。我想在我使用d3创建的SVG图表上添加一个html下拉菜单。目前,下拉菜单显示在图表下方,但我希望下拉菜单显示在图表上的特定位置。

我不清楚我的问题是否与浏览器呈现所有元素的顺序有关,或者它只是一个CSS问题。

任何帮助都将不胜感激。

这是我的html:

<div class="chartArea">
  <select class = "demoSelection"></select></div>

这是我的css:

  .chartArea{
      position: relative;}

    .demoSelection {
      position: absolute;
      width: 250px;
      top:400px;
      left:250px;}

这是我在d3中创建SVG元素的地方:

  var svg = d3.select("body").select(".chartArea")
      .append("svg")
      .attr("id","svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
      .append("g")
      .attr("class","chart");

我稍后使用d3

中的选项填充选择框
  d3.select(".demoSelection")
       .append("option")
       .attr("value",demoCounter)
       .text(json.demos[demoCounter].title);

2 个答案:

答案 0 :(得分:1)

我没有看到您提供的脚本中的任何错误。

我尝试使用您提供的输入重新创建场景,但无法重新创建但是我正在使用我的工作代码。

这可能会对你有帮助。

&#13;
&#13;
var svg = d3.select("body").select(".chartArea")
    .append("svg")
    .attr("id", "svg")
    .attr("width", 500)
    .attr("height", 500)
    .append("g").attr("class", "chart");

var data = [4, 8, 15, 16, 23, 42];

var width = 420,
    barHeight = 20;

var x = d3.scale.linear()
    .domain([0, d3.max(data)])
    .range([0, width]);



var bar = svg.selectAll("g")
    .data(data)
  .enter().append("g")
    .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

bar.append("rect")
    .attr("width", x)
    .attr("height", barHeight - 1);

bar.append("text")
    .attr("x", function(d) { return x(d) - 3; })
    .attr("y", barHeight / 2)
    .attr("dy", ".35em")
    .text(function(d) { return d; });

d3.select(".demoSelection")
    .append("option")
    .attr("value", 1)
    .text("Hello");
d3.select(".demoSelection")
    .append("option")
    .attr("value", 2)
    .text("Another Hello");
&#13;
.chartArea {
    position: relative;
}
.demoSelection {
    position: absolute;
    width: 100px;
    top:40px;
    left:25px;
}
.chart rect {
  fill: steelblue;
}

.chart text {
  fill: white;
  font: 10px sans-serif;
  text-anchor: end;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div class="chartArea">
    <select class="demoSelection"></select>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

尝试在CSS中为您的demoSelection类添加z-index: 10;