2012-07-06 19 views
1

我剛開始學習D3。我正在玩數組中的表格(來自教程中的示例),我想知道在mouseover上突出顯示一列的最佳方式是什麼?以下是我的第一次嘗試。D3中鼠標懸停時突出顯示錶格列的最有效方法是什麼?

var tableData = [], colCnt = 100, rowCnt = 100; 
    //Generate 2d array with values 
    for(var i=0; i<rowCnt; i++){ 
     tableData.push(d3.range(i*colCnt, (i*colCnt)+colCnt)) 
    } 

    d3.select('#viz').append('table') 
      .style('border-collapse', 'collapse') 
      .style('border', '2px solid black') 
     .selectAll('tr') 
     .data(tableData) 
     .enter().append('tr') 
      //Highlight the row 
      .on('mouseover', function(){d3.select(this).style('background-color', 'gray');}) 
      .on('mouseout', function(){d3.select(this).style('background-color', 'white');}) 
     .selectAll('td') 
     .data(function(d){ return d; }) 
     .enter().append('td') 
      .text(String) 
      .style('border', '1px solid black') 
      .style('padding', '5px') 
      //Highlight the column 
      .on('mouseover', function(d,i){ 
       //d3.select(this).style('background-color','lightgray'); 
       d3.select(this.parentNode.parentNode).selectAll('tr') 
        .selectAll('td') 
         .style('background-color', function(d,j){ return i==j ? 'lightgray' : null;}); 
      }) 
      .on('mouseout', function(d,i){ 
       //d3.select(this).style('background-color', null); 
       d3.select(this.parentNode.parentNode).selectAll('tr').selectAll('td').style('background-color', null); 
      }) 

[更新] 我想喬希的解決方案,它比上面我所要快得多。以下是更新版本。我將表格設置爲256x256,我沒有注意到任何放緩,上述解決方案有很大的延遲。

d3.select('#viz').append('table') 
      .style('border-collapse', 'collapse') 
      .style('border', '2px solid black') 
     .selectAll('tr') 
     .data(tableData) 
     .enter().append('tr') 
      .on('mouseover', function(){d3.select(this).style('background-color', 'gray');}) 
      .on('mouseout', function(){d3.select(this).style('background-color', 'white');}) 
     .selectAll('td') 
     .data(function(d){ return d; }) 
     .enter().append('td') 
      .text(String) 
      .style('border', '1px solid black') 
      .style('padding', '5px') 
      .attr('class', function(d,i){ return "col_" + i; }) 
      .on('mouseover', function(d,i){ 
       d3.selectAll('td.col_' + i) 
        .style('background-color', 'lightgray'); 
      }) 
      .on('mouseout', function(d,i){ 
       d3.selectAll('td.col_' + i) 
        .style('background-color', null); 
      }) 

回答

3

這似乎是一個合理的方式來實現自己的目標,你也可以考慮給各行不同的類名,即ROW1,ROW2,等,然後通過類選擇行,即:

.on('mouseover', function(d,i){ 
    d3.select(".row" + i) 
     .style('background-color', 'lightgray); 
}) 

我敢肯定,可能還有很多其他變種也可以做到這一點

相關問題