Javascript:滚动到表中的第n行? [英] Javascript: Scroll to nth row in a table?

查看:148
本文介绍了Javascript:滚动到表中的第n行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用纯Javascript或jQuery,如何滚动页面以便表中的第n行位于页面中心?



看到有这种功能通常要求我滚动的元素使用一个id作为选择器,但由于表具有动态数量的行,并可能被分页,我宁可不走这条路线必须给每个< td> 标记一个id。

是计算td相对位置的最简单方法使用setInterval滚动窗口,直到窗口的中间位置> =到第n个< td> 标记的位置?



我假设我设想它的一些伪代码是:

  function scrollToNthTD(i){
var position = CalculatePositionOfTR(i);
var timer = setTimeout(function(){
ScrollDownALittle();
if(CenterOfVerticalWindowPosition> position)
clearInterval(timer);
},100);


解决方案

既然你可以在这里使用jQuery它是..

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

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

Demo at http://jsfiddle.net/SZKJh/






如果您想让它动起来只是去那里使用

  var w = $(window); 
var row = $('#tableid')。find('tr')。eq(line); $()。
$ b if(row.length){
$('html,body')。animate({scrollTop:row.offset()。top - (w.height()/ 2) },1000);
}

Demo at http://jsfiddle.net/SZKJh/1/


Using either pure Javascript or jQuery, how do I scroll the page so that the nth row in a table is centered on the page?

Some examples I've seen that have this sort of feature usually require that the element I scroll to uses an id as the selector, but since the table has a dynamic amount of rows and may be paged, I'd rather not go this route of having to give each <td> tag an id.

Is the easiest way to just calculate the position of the td relative to the top of the document and scroll the window using setInterval until the middle of the window is >= to the position of the nth <td> tag?

I suppose some pseudo-code of the way I imagine it working would be:

function scrollToNthTD(i) {
  var position = CalculatePositionOfTR(i);
  var timer = setTimeout(function () {
    ScrollDownALittle();
    if( CenterOfVerticalWindowPosition > position)
      clearInterval(timer);
  }, 100);
}

解决方案

Since you can use jQuery here it is..

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

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

Demo at http://jsfiddle.net/SZKJh/


If you want it to animate instead of just going there use

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

if (row.length){
    $('html,body').animate({scrollTop: row.offset().top - (w.height()/2)}, 1000 );
}

Demo at http://jsfiddle.net/SZKJh/1/

这篇关于Javascript:滚动到表中的第n行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆