javascript 如何以编程方式将表滚动到特定的 tr

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22855341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:53:12  来源:igfitidea点击:

How to scroll table to particular tr programmatically

javascriptjqueryhtml

提问by V-Xtreme

I want to scroll the html table to particular tr by using Javascript or jquery. Currently I can get the offset of the selected tr .And I am using the scrollTop method .I have tried the following but it is not working for me :

我想使用 Javascript 或 jquery 将 html 表滚动到特定的 tr。目前我可以获得所选 tr 的偏移量。我正在使用 scrollTop 方法。我尝试了以下方法,但它对我不起作用:

var table  = document.getElementById("table");
var tr = table.getElementsByTagName("tr")[3];
var scrollTo = tr.offsetTop;
table.scrollTop = scrollTo;

also I tried with jquery :

我也试过 jquery :

$('#table').animate({scrollTop:0},50);

can anybody help me where am I getting wrong ?

谁能帮我我哪里出错了?

回答by Prashanth vunnam gcs

This worked for me, try this

这对我有用,试试这个

var elm = document.getElementById(id);
elm.scrollIntoView(true);

回答by Dipali Vasani

try this : http://jsfiddle.net/SZKJh/

试试这个:http: //jsfiddle.net/SZKJh/

var w = $(window);
var row = $('#tableid').find('tr').eq( line );

if (row.length){
    w.scrollTop( row.offset().top - (w.height()/2) );
}

reference :

参考 :

https://stackoverflow.com/a/7853216/1982680

https://stackoverflow.com/a/7853216/1982680

回答by Selvamani

Here the simpel step for scroll top function

这里是滚动顶部功能的简单步骤

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

Here the Demo

这里的演示