2017-03-03 238 views
1

根據this D3.js雷達圖表的例子,我試圖找到更高級的工具提示。我想顯示一個名稱和數字列表,其中一些基於我的數據集,而不僅僅是一個數字。D3.js雷達圖表工具提示

的問題是在這部分代碼:

blobCircleWrapper.selectAll(".radarInvisibleCircle") 
         .data(function(d,i) { return d; }) 
         .enter().append("circle") 
         .attr("class", "radarInvisibleCircle") 
         .attr("r", cfg.dotRadius*1.5) 
         .attr("cx", function(d,i){ return rScale(d.value) * Math.cos(angleSlice*i - Math.PI/2); }) 
         .attr("cy", function(d,i){ return rScale(d.value) * Math.sin(angleSlice*i - Math.PI/2); }) 
         .style("fill", "none") 
         .style("pointer-events", "all") 
         .on("click", function(d,i) { // TOOLTIP WITH SUBJECTS AND AVERAGES HERE 
          newX = parseFloat(d3.select(this).attr('cx')) - 10; 
          newY = parseFloat(d3.select(this).attr('cy')) - 10; 

          tooltip 
           .attr('x', newX) 
           .attr('y', newY) 
           .html(d.value+ "<br>" + "To:") 
           .transition().duration(200) 
           .style('opacity', 1); 
         }) 
         .on("mouseout", function(){ 
          tooltip.transition().duration(200) 
           .style("opacity", 0); 
         }); 


        //Set up the small tooltip for when you hover over a circle 
        var tooltip = g.append("text") 
         .attr("class", "tooltip") 
         .style("opacity", 0); 

工具提示設置爲雷達的圈子,當我嘗試創建一個div元素text元素的替代,工具提示停止顯示,雖然元素被創建並且定位良好。我正在嘗試這樣的事情:

​​

我確定我在這裏錯過了一些屬性,但有沒有辦法讓更完整的工具提示?謝謝。

回答

2

您正在使用<div>作爲工具提示。因此,你在這裏有一些不同的規則。

首先,你不能附加一個div到一個SVG(我想你的片段中的g選擇是一個SVG組)。您必須將div附加到正文(或任何其他HTML元素)。

其次,當您將div附加到HTML中時,不能將xy位置設置爲屬性。取而代之的是,您必須使用event.pageXevent.pageY,並將absolute定位爲div。

這裏是基礎知識非常簡單的演示OS剛纔說的:

var tip = d3.select("body") 
 
    .append("div") 
 
    .attr("class", "tip") 
 
    .style("opacity", 0); 
 

 
d3.select("svg") 
 
    .selectAll("foo") 
 
    .data(d3.range(7)) 
 
    .enter() 
 
    .append("circle") 
 
    .attr("cx", d => 20 + d * 40) 
 
    .attr("cy", 50) 
 
    .attr("r", 15) 
 
    .attr("fill", "teal") 
 
    .on("mousemove", (d, i) => { 
 
     tip.html("This is the<br>circle number " + i) 
 
      .style("left", d3.event.pageX + 10 + "px") 
 
      .style("top", d3.event.pageY + "px") 
 
      .style("opacity", 1) 
 
    }).on("mouseout",() => { 
 
     tip.style("opacity", 0) 
 
    })
.tip{ 
 
    position: absolute; 
 
    padding: 10px; 
 
    background: lightgray; 
 
    border: 1px solid black; 
 
    pointer-events: none; 
 
}
<script src="https://d3js.org/d3.v4.min.js"></script> 
 
<svg></svg>

+0

是啊,你說得對。創建這些工具提示時,我總是傾向於迷惑自己。我總是將'div'元素附加到SVG,而不是附加到body。我現在不會忘記它。謝謝。在附註中,你認爲這些是最好的工具提示類型嗎? –

+0

@ Shoplifter.Doe好吧,「最佳類型」是基於意見的......我只能說這些是我在代碼中使用的工具提示。 –

+1

是的,我知道,但我歡迎您提出意見,因爲您是一位熟練的D3.js用戶和貢獻者。謝謝 :) –