跳转到 table 行并在 html 中突出显示它?

Jump to table row and Highlight it in html?

我有一个很长的 table 并且不同的条目彼此相关,所以我 link 他们喜欢这样:

<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 is related" 时跳下页面(这有效),但随后我希望这一行很快亮起以指出是哪一行。 有什么办法吗?

如果可以接受一点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>

您需要一个 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>