将增长的页面滚动到底部

我有一个页面。 当我手动滚动它,它会增长,然后我可以反复滚动它,直到滚动到达底部(一个很好的例子是Facebook时间线页面)。

我试着写:

static IWebDriver driver = new ChromeDriver(@"C:\selenium\net40"); IJavaScriptExecutor js = driver as IJavaScriptExecutor; 

然后我进入了一个页面并做了:

 js.ExecuteScript("window.scroll(0, document.height)"); 

但我可以滚动更多。

即使页面正在增长,如何才能滚动到底部?

任何帮助赞赏!

window.scroll(0, document.height)将滚动到已知的可滚动区域。 问题是当您到达页面底部时会下载更多数据。 因此,可滚动区域被更改。 您需要根据需要滚动多次。

例如,使用此脚本

 var timeId = setInterval( function() { if(window.scrollY!==document.body.scrollHeight) window.scrollTo(0,document.body.scrollHeight); else clearInterval(timeId); },500); 

编辑:

在某些页面上, window.scrollY将永远不会等于document.body.scrollHeight ,因此永远不会清除setIntervanl:这将阻止您转到顶部。

 var timeId = setInterval( function() { if(window.scrollY<(document.body.scrollHeight-window.screen.availHeight)) window.scrollTo(0,document.body.scrollHeight); else { clearInterval(timeId); window.scrollTo(0,0); } },500); 

遗憾的是,当页面的总高度发生变化时,不会触发任何事件。 因此,有两种可能的解决方案:

您可以使用计时器“盲目地”每隔一段时间滚动到底部。

 setInterval(function () { window.scroll(0, document.height); }, 100); 

或者,您可以使用“DOMSubtreeModified”事件在每次高度更改时滚动到底部。 每次文档中的任何更改都会触发此事件,因此如果您经常更改DOM,可能会降低浏览器的速度。 但是,此解决方案可确保您在页面增长时立即滚动到底部。

 //scroll to bottom when anything changes in the dom tree. var height = document.height; document.addEventListener('DOMSubtreeModified', function () { if (document.height != height) { height = document.height; window.scroll(0, height); } }); 

我对目标很满意,但从用户的角度来看,不是建议的代码方法。 如果我登陆的页面中有一个设计需要部分使用ajax(或任何其他方法)加载所有内容,我会期望页面默默地执行它而不会打扰我不必要的滚动。 因此,最好的方法是在加载更多内容的情况下,一个接一个地在后台进行调用。 如果您同意此解决方案,那么通常您需要window.onload事件的函数来进行第一次调用,处理响应并调用自身以获取更多内容。

以下两个函数将强制您的页面在加载新内容时滚动:

JS:

 var attachScrollModified = function () { document.addEventListener('DOMSubtreeModified', function () { this.removeEventListener('DOMSubtreeModified', arguments.callee, false); window.scroll(0, getBottomElemPos()); attachScrollModified(); }); } var getBottomElemPos = function () { var scrollElem = document.getElementById("scrollElem"); if (scrollElem) { document.body.removeChild(scrollElem); } scrollElem = document.createElement("div"); scrollElem.id = "scrollElem"; document.body.appendChild(scrollElem); return scrollElem.offsetTop; } 

示例: http : //jsfiddle.net/MaxPRafferty/aHGD6/

将它们放在页面上的 ,然后调用:

 js.ExecuteScript("attachScrollModified();"); 

也就是说,这可能会导致无限循环,不断激发更多内容。

Interesting Posts