簡體   English   中英

模仿<a>hover 和點擊 javascript 的行為</a>

[英]Mimic <a> behavior on hover and on click with javascript

我有一個表,每一行都應該鏈接到一個頁面。

我想保持 html 的結構不變(不是一堆 div 和網格,例如在 <a> 標簽中包裝 HTML 表行

一切都適用於 javascript,但我缺少左下角的工具提示,該提示顯示標簽中的 hover 上的 url。 我還想要使用 CMD (mac) 或 CTRL (windows/linux) 在新選項卡中打開的選項。

我目前正在使用 jQuery 解決問題:

 $('.clickable-row').on('click', function () { const url = $(this).attr('data-url') if (typeof url === 'string') { window.location.href = url } });

我的 html(樹枝):

 <table class='table'> <thead> <tr> {% for h in data.header %} <th>{{h|trans}}</th> {% endfor %} </tr> </thead> <tbody> {% for row in data.rows %} {% set url = data.getOnClickURL(loop.index - 1) %} <tr {% if url %} class='clickable-row' data-url="{{url}}" {% endif %}> {% for r in row %} <td>{{r|trans}}</td> {% endfor %} </tr> {% endfor %} </tbody> </table>

嘗試此解決方案,而無需僅使用 HTML 和 CSS 編寫 Javascript 代碼。

 table { width: 100%; border-collapse: collapse; } table tr { position: relative; } table tr td { border: 1px solid black; text-align: center; } table tr a { position: absolute; width: 100%; display: block; height: 100%; top: 0px; left: 0px; }
 <table> <tr> <td><a href="https://google.com"></a> 1 </td> <td>2 </td> <td>3 </td> </tr> <tr> <td><a href="https://github.com"></a>1 </td> <td>2 </td> <td>3 </td> </tr> <tr> <td><a href="https://stackoverflow.com/"></a>1 </td> <td>2 </td> <td>3 </td> </tr> <tr> <td>1 </td> <td>2 </td> <td>3 </td> </tr> <tr> <td>1 </td> <td>2 </td> <td>3 </td> </tr> </table>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM