要實作的效果是點選每個柱的時候都要傳回他的數值,而這個數值我選擇将其綁定在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"));
}
效果:
他的dom結構是這樣的:
效果圖中我還為rect綁定了mouseenter, mousemove, mouseout事件,完整代碼如下:
//這是懸浮提示框
var div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", );
......
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 - ) + "px");
div.transition()
.duration()
.style("opacity", )
}
function getData() {
alert($(this).attr("value"));
}
function setTip(obj) {
return $(obj).attr("value");
}
function hideTip() {
div.transition()
.duration()
.style("opacity", )
}
其中懸浮提示框的樣式如下:
div.tooltip {
position: fixed;
text-align: center;
width: px;
height: px;
padding: px;
background: lightsteelblue;
border: px;
border-radius: px;
pointer-events: none;
}
此文檔的作者:justforuse
Github Pages:justforuse