如何在 javascript 中正确地将 IFrame 滚动到底部

Roe*_*erg 6 html javascript iframe

对于用于研究网站交互的模型网页,我使用 JavaScript 创建了一个模型消息流。此消息流加载到 IFrame 中,并应按预设的时间间隔显示图像,并在将新图像放置在页面底部后滚动到页面底部。使用提供的脚本可以很好地显示图像。然而,Chrome 和 IE 似乎都无法将页面滚动到底部。我想在附加图像后立即滚动到页面底部,但现在添加了 5 毫秒的延迟,因为这有时似乎有效。我的问题是:

  • 可以使用 document.body.scrollHeight 来实现此目的吗?
  • 我可以让滚动直接发生,还是需要在滚动之前有一个小的间隔?
  • 如何让代码在添加图片后直接滚动到IFrame的底部?

使用以下函数并在 Load 时启动 trypost():

function scrollToBottom(){
  window.scrollBy(0,document.body.scrollHeight);
}

function trypost(){
  point = point + 1;
  if(point < interval.length){
    //create and append a new image
    var newImg = document.createElement("IMG");
    newImg.src = "images/"+images[point]+".png";
    document.getElementById('holder').appendChild(newImg);
    //create and append a return
    var br = document.createElement("br");
    document.getElementById('holder').appendChild(br);
    //time scroll to bottom (after an arbitrary 5 seconds)
    var stb = window.setTimeout(scrollToBottom, 5);
    //time next post
    var nextupdate = interval[point]*400;
    var tp = window.setTimeout(trypost, nextupdate);
  }
}
Run Code Online (Sandbox Code Playgroud)

我的脚本部分至少包含以下变量:

var point = -1;
var interval = [10, 10, 15];
var images = ["r1", "a1", "r2"];
Run Code Online (Sandbox Code Playgroud)

这个问题是如何在 IE 中正确使用 setTimeout?中描述的项目的延续。

Tho*_*ban 3

滚动到底部总是就像滚动到某个大得离谱的顶部偏移量,例如999999

iframe.contentWindow.scrollTo( 0, 999999 );
Run Code Online (Sandbox Code Playgroud)

另外请参阅这篇文章:Scrolling an iframe with javascript?

如果滚动发生得太早,可能是由于图像尚未加载。因此,您必须在加载添加的图像后立即滚动,而不是在放置它时滚动。添加

newImg.onload = function() { triggerScrolling(); };
Run Code Online (Sandbox Code Playgroud)

创建之后newImg但分配属性之前src

如果需要多个事件来触发滚动,您可能需要使用一些“事件收集器”。

function getEventCollector( start, trigger ) {
    return function() {
        if ( --start == 0 ) { trigger(); )
    };
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用它:

var collector = getEventCollector( 2, function() { triggerScrolling(); } );
newImg.onload = collector;
window.setTimeout( collector, 100 );
Run Code Online (Sandbox Code Playgroud)

这种方式triggerScrolling()至少在 100 毫秒后调用,并且在图像加载后collector必须调用两次才能最终调用triggerScrolling()。