滚动到 iframe 中数据表的顶部

Scroll to top of datatable in an iframe?

本文关键字:顶部 数据表 iframe 滚动      更新时间:2023-09-26

我正在尝试向我的DataTables添加一个函数,当单击分页链接时,该函数会滚动到表格顶部,我按照这里的指南进行操作:

http://jsfiddle.net/EjbEJ/

function paginateScroll() {
  $('html, body').animate({
    scrollTop: $(".dataTables_wrapper").offset().top
  }, 100);
  console.log('pagination button clicked');
  $(".paginate_button").unbind('click', paginateScroll);
  $(".paginate_button").bind('click', paginateScroll);
}
paginateScroll();

这很完美,但不幸的是,我有DataTable的页面正在加载到 iframe 中,而在 iframe 中它不再工作。知道如何让这个脚本在 iframe 中工作吗?

是的,您必须使用 postMessage 与 iframe 通信,并且可能在两个位置都有您的代码,以便父框架可以向框架发送消息,然后框架可以执行滚动动画。

https://davidwalsh.name/window-postmessage

只是为了让你知道我解决了这个问题。我只需要添加$(parent.document).find来获取父框架的html和body标签。

function paginateScroll() {
  $(parent.document).find('html, body').animate({
    scrollTop: $(".dataTables_wrapper").offset().top
  }, 100);
  //console.log('pagination button clicked');
  $(".paginate_button").unbind('click', paginateScroll);
  $(".paginate_button").bind('click', paginateScroll);
}
paginateScroll();

干杯