如何正确制作D3事件监听器?

时间:2013-05-21 20:30:38

标签: javascript events d3.js listener

我有一些代码可以绘制一堆六边形,但是当我将鼠标悬停在它们上面时,我需要它们显示为白色并执行其他操作。为什么事件监听器不起作用,我需要做些什么呢?http://jsfiddle.net/rewBr/

var elementTags = ["Google", 4, "Wikipedia", "Yahoo!", "Cindy"];
var _s32 = (Math.sqrt(3)/2);
var A = 75;

var svgContainer = d3.select("body") //create container
    .append("svg")
    .attr("width", 1000)
    .attr("height", 1000);
var xDiff = [0, 200, 400, 600, 800, 1000, 1200, 1400];
var yDiff = [200, 200, 200, 200, 200, 200, 200];

for (index = 0; index < elementTags.length; index++) { var pointData = [ [A+xDiff[index], 0+yDiff[index]], [A/2+xDiff[index], (A*_s32)+yDiff[index]], [-A/2+xDiff[index], (A*_s32)+yDiff[index]], [-A+xDiff[index], 0+yDiff[index]], [-A/2+xDiff[index], -(A*_s32)+yDiff[index]], [A/2+xDiff[index], -(A*_s32)+yDiff[index]], [A+xDiff[index], 0+yDiff[index]]];

    var hexMouseOver = function(){
        console.log(this);
        this.style("fill", "white");
    }

var enterElements = svgContainer.selectAll("path.area") //draw element
    .data([pointData]).enter().append("path")
    .style("fill", "#1D85E0")
    .style("stroke", "black")
    .attr("d", d3.svg.line())
    .style("shape-rendering", "auto")
    .on("mouseover", hexMouseOver);

}     var addText = svgContainer.selectAll("text").data(elementTags).enter().append("text");

var textElements = addText
            .attr("x", function(d, i){
                return xDiff[i];})
            .attr("y", function(d, i){
                return yDiff[i];})
            .attr("font-family", "Arial Black")
            .attr("font-size", "20px")
            .attr("fill", "1A2E40")
            //.attr("font-variant", "small-caps")
            .style("text-anchor", "middle")
            .text(function(d, i){return d;});

1 个答案:

答案 0 :(得分:5)

你需要先用d3选择'this'元素:

.on("mouseover", function(){
    console.log(this);
    console.log(d3.select(this));
    d3.select(this).style("fill", "white");})

更新小提琴:http://jsfiddle.net/rewBr/3/

相关问题