简体   繁体   English

通过单击表行将表行滚动到div的顶部

[英]Scroll table row to top of div by clicking the row

Basically, I have a table that has many rows. 基本上,我有一个包含许多行的表。 What I want to do is scroll the row I click to the top of the div that encases the table. 我想做的就是将我单击的行滚动到包含表格的div顶部。

Here is the StackOverflow question I started from: How to scroll table to particular tr programmatically 这是我开始的StackOverflow问题: 如何以编程方式将表格滚动到特定的tr

Basically, this person was able to make the table jump to the table row he wanted by manually putting the in nth-child number like so: 基本上,此人可以通过手动输入第n个子代号来使表跳至所需的表行:

var s = $("table tbody > tr:nth-child(20)").position();
$( "div" ).scrollTop( s.top );

Here is the fiddle he worked on showing it working for manually setting the nth-child in the code: http://jsfiddle.net/4Z7Z9/ 这是他致力于显示的小提琴,用于手动设置代码中的nth-child: http : //jsfiddle.net/4Z7Z9/

Here is how I changed the code : 这是我更改代码的方式

function scrollThisToTop(row) {
    var s = $("table tbody > tr:nth-child(" + row + ")").position();
    $( "div" ).scrollTop( s.top );
}

Here is my fiddle I am working on: http://jsfiddle.net/4Z7Z9/210/ 这是我正在研究的小提琴: http : //jsfiddle.net/4Z7Z9/210/

Any help greatly appreciated! 任何帮助,不胜感激!

I was able to get it working in 3 simple steps. 我能够通过3个简单的步骤使其工作。 Checkout the solution in fiddle HERE 此处检出解决方案

You will need to add on click functionality as well as and ID for your containing div. 您需要为包含的div添加点击功能以及ID。

The new Function: 新功能:

function scrollThisToTop(row) {

  // Get the id of the row
  var myElement = row.id;

  // Get the variable for the top of the row
    var topPos = row.offsetTop;

  // The container div top to the row top
  document.getElementById('container').scrollTop = topPos;

}

On click functionality: 点击功能:

$('tr').on("click", function () {
    scrollThisToTop(this);
});

Div id: div ID:

<div id="container">

This helps you? 这对您有帮助吗?

$('table tr').bind('click', function() {
   var s = $('table').position();
   $('div').scrollTop(s);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM