lishengzxc / bblog

My Blog
https://github.com/lishengzxc/bblog/issues
178 stars 8 forks source link

表格十字线聚焦效果续(纯CSS) #14

Open lishengzxc opened 8 years ago

lishengzxc commented 8 years ago

之前写过一篇表格十字线聚焦效果的分享 #11 ,但是用到了 JS,后来发现可以完全利用 CSS 来实现。

原理

通过td:hover配合::before或::after,并且将其高度设置无限高,同时改变::after::before的z-index值为 -1(让高亮的背景色变为下层)。重要的一点,需要给table设置一个overflow:hidden,将伪元素溢出的高度截取掉。

show code~

html

<main>
  <table>
    <thead>
      <tr>
        <th></th>
        <th class="col">50kg</th>
        <th class="col">55kg</th>
        <th class="col">60kg</th>
        <th class="col">65kg</th>
        <th class="col">70kg</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th class="row">160cm</th>
        <td>20</td>
        <td>21</td>
        <td>23</td>
        <td>25</td>
        <td>27</td>
      </tr>

      <tr>
        <th class="row">165cm</th>
        <td>18</td>
        <td>20</td>
        <td>22</td>
        <td>24</td>
        <td>26</td>
      </tr>

      <tr>
        <th class="row">170cm</th>
        <td>17</td>
        <td>19</td>
        <td>21</td>
        <td>23</td>
        <td>25</td>
      </tr>

      <tr>
        <th class="row">175cm</th>
        <td>16</td>
        <td>18</td>
        <td>20</td>
        <td>22</td>
        <td>24</td>
      </tr>
    <tbody>
  </table>
</main>

css

table {
  overflow: hidden;
}

td, th {
  padding: 10px;
  position: relative;
  outline: 0;
}

tbody tr:hover {
  background-color: red;
}

td:hover::after,
thead th:not(:empty):hover::after,
td:focus::after,
thead th:not(:empty):focus::after { 
  content: '';  
  height: 10000px;
  left: 0;
  position: absolute;  
  top: -5000px;
  width: 100%;
  z-index: -1;
}

td:hover::after,
th:hover::after {
  background-color: red;
}

refer