how to make a whole row in a table clickable as a link?

前端 未结 26 1592
粉色の甜心
粉色の甜心 2020-11-22 14:05

I\'m using Bootstrap and the following doesn\'t work:


    
        
            Blah Blah
           


        
相关标签:
26条回答
  • 2020-11-22 14:36

    You could give the row an id, e.g.

    <tr id="special"> ... </tr>

    and then use jquery to say something like:

    $('#special').onclick(function(){ window="http://urltolinkto.com/x/y/z";})

    0 讨论(0)
  • 2020-11-22 14:38

    I've invested a lot of time trying to solve this problem.

    There are 3 approaches:

    1. Use JavaScript. The clear drawbacks: it's not possible to open a new tab natively, and when hovering over the row there will be no indication on status bar like regular links have. Accessibility is also a question.

    2. Use HTML/CSS only. This means putting <a> nested under each <td>. A simple approach like this fiddle doesn't work - Because the clickable surface is not necessarily equal for each column. This is a serious UX concern. Also, if you need a <button> on the row, it is not valid HTML to nest it under <a> tag (although browsers are ok with that).

      I've found 3 other ways to implement this approach. First is ok, the other two are not great.

      a) Have a look on this example:

      tr {
        height: 0;
      }
      
      td {
        height: 0;
        padding: 0;
      }
      
      /* A hack to overcome differences between Chrome and Firefox */
      @-moz-document url-prefix() {
        td {
          height: 100%;
        }
      }
      
      a {
        display: block;
        height: 100%;
      }
      

      It works, but due to inconsistencies between Chrome and Firefox it requires browser-specific hack to overcome the differences. Also Chrome will always align the cell content to the top, which can cause problems with long texts, especially if varying line heights are involved.

      b) Setting <td> to { display: contents; }. This leads to 2 other problems:

      b1. If someone else tries to style directly the <td> tag, like setting it to { width: 20px; }, we need to pass that style somehow to the <a> tag. We need some magic to do that, probably more magic than in the Javascript alternative.

      b2. { display: contents; } is still experimental; specifically it's not supported on Edge.

      c) Setting <td> to { height: --some-fixed-value; }. This is just not flexible enough.

    3. The last approach, which I recommend to seriously thinking of, is to not using clickable rows at all. Clickable rows is not a great UX experience: it's not easy to visually mark them as clickable, and it poses challenges when multiple parts are clickable within the rows, like buttons. So a viable alternative could be to have an <a> tag only on the first column, displayed as a regular link, and give it the role of navigating the whole row.

    0 讨论(0)
提交回复
热议问题