d3中为每个rect元素绑定带数据的点击事件

                       

要实现的效果是点击每个柱的时候都要返回他的数值,而这个数值我选择将其绑定在value属性上(其实属性名可以自定义,但是不要使用abc这种没有意义的属性)

然后正常使用d3中的时间绑定方法绑定rect元素。

代码:

svg.selectAll(".bar")    .data(dataset)    .enter()    .append("rect")    //do something other...    .attr("value", function(d) {        return d.value;    })//为每个rect元素绑定click事件svg.selectAll("rect")    .on("click", getData)function getData() {    //这里我使用了jquery,dom操作感觉比较方便    alert($(this).attr("value"));}
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

效果:
这里写图片描述

他的dom结构是这样的:
这里写图片描述

效果图中我还为rect绑定了mouseenter, mousemove, mouseout事件,完整代码如下:

//这是悬浮提示框var div = d3.select("body").append("div")    .attr("class", "tooltip")    .style("opacity", 0);......svg.selectAll("rect")        .on("click", getData)        .on("mouseenter", showTip)        .on("mousemove", showTip)        .on("mouseout", hideTip)    function showTip() {        //定义悬浮框的位置        div.html(setTip(this))            .style("left", (d3.event.pageX) + "px")            .style("top", (d3.event.pageY - 28) + "px");        div.transition()            .duration(300)            .style("opacity", 0.9)    }    function getData() {        alert($(this).attr("value"));    }    function setTip(obj) {        return $(obj).attr("value");    }    function hideTip() {        div.transition()            .duration(100)            .style("opacity", 0)    }
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

其中悬浮提示框的样式如下:

div.tooltip {    position: fixed;    text-align: center;    width: 60px;    height: 28px;    padding: 2px;    background: lightsteelblue;    border: 0px;    border-radius: 8px;    pointer-events: none;}
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11


此文档的作者:justforuse
Github Pages:justforuse

           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

猜你喜欢

转载自blog.csdn.net/qq_43682817/article/details/86424527
今日推荐