跳到表格行并用html突出显示?

时间:2018-10-11 15:53:59

标签: html html-table row highlight

我有一张长桌子,并且不同的条目彼此相关,所以我将它们链接为:

<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与之相关”时,我跳下页面(这是可行的),但是我希望此行很快点亮以指出是哪一行。 有什么可以做的吗?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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