【问题标题】:Jump to table row and Highlight it in html?跳转到表格行并在 html 中突出显示它?
【发布时间】:2019-03-16 18:50:15
【问题描述】:

我有一个长表,不同的条目相互关联,所以我将它们链接成这样:

<tr>
    <th>Thing </th>
    <th>related to Thing </th>
</tr>
<tr>
    <td><a name = "t1"/>Thing 1</td>
    <td><a href = "#t2">Thing2 is related </a></td>
</tr>
<tr>
    <td><a name = "t2"/>Thing2</td>
    <td><a href = "#t1">Thing1 is related </a></td>
</tr>

现在,我希望当我单击“Thing2 相关”时,我会跳下页面(这很有效),但我希望该行很快亮起以指出哪一行是指的。 有什么办法吗?

【问题讨论】:

    标签: html html-table row highlight


    【解决方案1】:

    您需要一个 onclick 函数,以便在单击相关超链接时它知道要突出显示的内容。

    function highlight(selector) {
      var highlighted = document.querySelector("a[name=" + selector + "]");
      var originalColor = highlighted.style.backgroundColor;
      highlighted.style.backgroundColor = "yellow";
      setTimeout(function() {
        highlighted.style.backgroundColor = originalColor;
      }, 1000);
    }
    
    function setHighlightCall(selector) {
      return function() {
        highlight(selector);
      };
    }
    
    window.onload = function() {
      var anchors = document.querySelectorAll("a[href^='#']");
      anchors.forEach(function(anchor) {
        var anchorName = anchor.href.match(/#([^#]+)$/)[1];
        anchor.onclick = setHighlightCall(anchorName);
      });
    };
    <tr>
      <td><a name="t1"/>Thing 1</td>
      <td><a href="#t2">Thing2 is related </a></td>
    </tr>
    <div style="height:500px"></div>
    <tr>
      <td><a name="t2"/>Thing2</td>
      <td><a href="#t1">Thing1 is related </a></td>
    </tr>

    【讨论】:

    • 感谢你们俩,我发现在代码中的任何地方都不能有像 empty 这样的空链接(如果有的话)否则有一个类似的问题)
    • 这已经很好了,但是可以将文本背景更改为行背景
    • 您可以轻松地根据您的特定需求进行调整。试试parentNode
    【解决方案2】:

    如果可以接受一点 jQuery,那么可以。你必须对你的 html 做一个小改动,将name 属性更改为id

    // Listen for clicks on '.link' elements
    $('table').on('click', '.link', function() {
      // Find previously selected items and remove the class, restricting the search to the table.
      $('.related', 'table').removeClass('related')
      // Find the click target
      target = $(this).attr('href');
      // Find its 'tr' and highlight it
      $(target).closest('tr').addClass('related')
    });
    .related {
      background-color: #ccc;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table>
      <tr>
        <th>Thing </th>
        <th>related to Thing </th>
      </tr>
      <tr>
        <td><a id="t1" />Thing 1</td>
        <td><a class="link" href="#t2">Thing2 is related </a></td>
      </tr>
      <tr>
        <td><a id="t2" />Thing2</td>
        <td><a class="link" href="#t1">Thing1 is related </a></td>
      </tr>
    </table>

    【讨论】:

      猜你喜欢
      • 2011-02-21
      • 2013-07-12
      • 2011-12-05
      • 2011-05-14
      • 2014-02-04
      • 2012-04-14
      • 1970-01-01
      • 2010-10-20
      • 1970-01-01
      相关资源
      最近更新 更多