在d3词云中添加悬停效果

Adding hover effect in d3 word cloud

本文关键字:悬停 添加 d3      更新时间:2023-09-26

我正在使用D3云来构建词云(https://github.com/jasondavies/d3-cloud),我想添加类似于 http://www.jasondavies.com/wordcloud 的悬停效果。

下面是示例代码。完整的代码在 http://plnkr.co/edit/gNtHZ0lMRTP98mptm3W8?p=preview

     var sizeScale = d3.scale.linear()
         .domain([0, d3.max(frequency_list, function(d) { return d.freq} )]).range([10, 95]);

    layout = d3.layout.cloud().size([w, h])
    .words(frequency_list)
    .padding(5)
    .rotate(function() { return ~~(Math.random() * 2) * 90; })
    .font("Impact")
    .fontSize(function(d) { return sizeScale(d.freq); })
      .on("end",draw)
      .start();
}
function draw(words) {

var fill = d3.scale.category20();
    d3.select(container).remove();
    d3.select("body").append(container)
    .attr("width", w)
    .attr("height", h) 
        .append("g")
    .attr("transform", "translate(" + [w/2, h/2] + ")")
    .selectAll("text")
    .data(words)
    .enter().append("text")
    .transition()
    .duration(function(d) { return d.time}  )
    .attr('opacity', 1)
    .style("font-size", function(d) { return d.size + "px"; })
    .style("font-family", "Impact")
      .style("fill", function(d, i) { return fill(i); })
    .attr("text-anchor", "middle")
    .attr("transform", function(d) {
      return "rotate(" + d.rotate + ")";
    })
    .attr("transform", function(d) {
      return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
    })
    .text(function(d) { return d.text; });
}

在你链接到的页面上,他正在使用一个:hover伪类。

<style>
  text:hover { opacity: .7 !important; }
</style>

在此处更新了代码。