使用javascript水平滚动iframe

时间:2014-07-15 16:48:13

标签: javascript jquery iframe

我有一个iframe,我想用一些参数水平和垂直滚动。似乎我可以垂直滚动页面而没有问题,但我不能水平滚动它...

以下是一些代码示例:

HTML:

<iframe id="html-region" src="some local url" style="width:1000px;height:1000px;overflow:scroll" scrolling="yes"></iframe>

Javascript / jQuery:

// None worked
$('iframe').get(0).contentWindow.scroll(200, 0);
$('iframe').get(0).contentWindow.scrollTo(200, 0);
$('iframe').get(0).window.document.body.scrollLeft += 200;
$('iframe').scrollLeft(200);

提前谢谢!

1 个答案:

答案 0 :(得分:0)

你几乎就在那里:

$("#html-region").contents().find("body").scrollLeft(200);

要记住的一些事情:

  • Cross-Origin:您只能访问iframe的内容html,如果它与托管iframe的网页位于同一个原点:看看 Here
    - 因为你的网址是一些当地的网址&#39;不应该有任何问题。

  • 您需要等待iframe的内容完全加载,然后才能滚动它。我通常只是等到整个窗口的内容满载$(window).load(function(){块。

  • 不是获取所有iframe的列表并选择列表中的第一个iframe,而是通过它的id更好地解决iframe问题。您不知道将来会发生什么,您可能会在此之前添加另一个iframe,您可能会被迫更改您的代码。更好地避免这种情况。

尽管如此,这是一个有效的例子:

//block that will be executed once the iframe's content is fully loaded
$(window).load(function(){
    //get the body element inside of the iframe
    var $myFrameContent = $("#html-region").contents().find("body");
    //adjust the scrollLeft/Top
    $myFrameContent.scrollTop(200);
    $myFrameContent.scrollLeft(50);
});

这是 Fiddle