为新手问题道歉,但我正在尝试使用d3执行以下操作:
1)渲染交替的行为灰色和白色(斑马纹) 2)突出显示鼠标悬停事件中的行 3)在mouseout上将行返回到其原始状态
我通过以下代码完成了此操作,除了在mouseout上将行返回到原始颜色外,它的工作正常。相反,它只是将每一行渲染为mouseout上的#c4c4c4
var rows = tbody.selectAll("tr")
data(states)
.enter()
.append("tr")
.style("background-color", function(d, i) {
if (i%2===0){return "#fff";}else{return "#c4c4c4";}
});
var rows = tbody.selectAll("tr")
.on("mouseover", function(){
d3.select(this).style("background-color", "yellow");})
.on("mouseout", function(){
d3.select(this).style("background-color", function(d,i) {
if (i % 2 === 0){
return "#fff";
}
else {
return "#c4c4c4";
}
}
)}
答案 0 :(得分:1)
问题在于,当您重新选择this
元素时,该元素将成为确定内部(样式)回调函数的i
索引的选择。您需要mouseout事件处理函数中的i
索引:
.on("mouseout", function(d,i){ //correct index is passed here!
d3.select(this).style("background-color", function(d2,j) {
//d2 will be the same as d, but j will always be 0
//since d3.select(this) only has one element
if (i % 2 === 0){
return "#fff";
}
else {
return "#c4c4c4";
}
} )
});
您实际上不需要声明参数d2
和j
,因为它们从未使用过 - 为了清晰起见,我只是将它们包括在内。
顺便说一下,你可以用CSS做这两种效果:
tr:nth-of-type(2n) { /* even rows */
background-color: #c4c4c4;
}
tr:nth-of-type(2n+1) { /* odd rows */
background-color: #fff;
}
tr:hover { /* mouseover */
background-color: yellow;
}
请注意,在CSS中,元素从1开始编号,因此第一行被视为奇数行。