我有一个 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);
提前谢谢您!
最佳答案
你就快到了:
$("#html-region").contents().find("body").scrollLeft(200);
需要记住的一些事情:
跨源:如果 iframe 的内容 html 与托管 iframe 的页面位于同一源,则只能访问该内容:看看 Here
- 由于您的网址是“某些本地网址”,因此应该不会有任何问题。您需要等待 iframe 的内容完全加载,然后才能滚动它。我通常只是等到整个窗口的内容完全加载
$(window).load(function(){
block 。与其获取所有 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
关于javascript - 使用 javascript 水平滚动 iframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24763802/