raw*_*rrr 49 javascript iframe scroll
我用JavaScript动态加载iframe.加载后,如何让它向下滚动特定数量的像素(即在iframe中的页面加载后,如何将iframe自身滚动到页面的指定区域?)
CMS*_*CMS 45
您可以使用该onload事件来检测iframe何时完成加载,并且您可以在iframe的contentWindow上使用scrollTo函数,从左侧和顶部(x,y)滚动到像素的已定义位置:
var myIframe = document.getElementById('iframe');
myIframe.onload = function () {
myIframe.contentWindow.scrollTo(xcoord,ycoord);
}
Run Code Online (Sandbox Code Playgroud)
你可以在这里查看一个工作示例.
注意:如果两个页面都位于同一个域中,则此方法有效.
小智 19
受到Nelsons评论的启发,我做到了这一点.
javascript的解决方法关于在源自外部域的文档上使用.ScrollTo()的相同原始策略.
非常简单的解决方法是创建一个虚拟html页面,在其中托管外部网站,然后在加载后在该页面上调用.ScrollTo(x,y).那么你唯一需要做的就是让一个框架或iframe打开这个网站.
还有很多其他方法可以做到这一点,这是迄今为止最简单的方法.
*注意高度必须很大才能容纳滚动条的最大值.
--home.htm
<html>
<head>
<title>Home</title>
</head>
<frameset rows="*,170">
<frame src=body.htm noresize=yes frameborder=0 marginheight=0 marginwidth=0 scrolling="no">
<frame src="weather.htm" noresize=yes frameborder=0 marginheight=0 marginwidth=0 scrolling="no">
</frameset>
</html>
Run Code Online (Sandbox Code Playgroud)
--weather.htm
<html>
<head>
<title>Weather</title>
</head>
<body onLoad="window.scrollTo(0,170)">
<iframe id="iframe" src="http://forecast.weather.gov/MapClick.php?CityName=Las+Vegas&state=NV&site=VEF&textField1=36.175&textField2=-115.136&e=0" height=1000 width=100% frameborder=0 marginheight=0 marginwidth=0 scrolling=no>
</iframe>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
Son*_*tos 13
在尼尔森和克里斯的评论的启发下,我找到了一种解决同一起源政策的方法div,其中包括iframe:
HTML:
<div id='div_iframe'><iframe id='frame' src='...'></iframe></div>
Run Code Online (Sandbox Code Playgroud)
CSS:
#div_iframe {
border-style: inset;
border-color: grey;
overflow: scroll;
height: 500px;
width: 90%
}
#frame {
width: 100%;
height: 1000%; /* 10x the div height to embrace the whole page */
}
Run Code Online (Sandbox Code Playgroud)
现在假设我想通过滚动到该位置跳过iframe页面的前438个(垂直)像素.
JS解决方案:
document.getElementById('div_iframe').scrollTop = 438
Run Code Online (Sandbox Code Playgroud)
JQuery解决方案:
$('#div_iframe').scrollTop(438)
Run Code Online (Sandbox Code Playgroud)
CSS解决方案:
#frame { margin-top: -438px }
Run Code Online (Sandbox Code Playgroud)
(单独的每个解决方案都足够了,CSS的效果有点不同,因为你无法向上滚动以查看iframed页面的顶部.)
使用scrollTop框架内容的属性将内容的垂直滚动偏移设置为特定数量的像素(如 100):
<iframe src="foo.html" onload="this.contentWindow.document.documentElement.scrollTop=100"></iframe>
Run Code Online (Sandbox Code Playgroud)
一个 jQuery 解决方案:
$("#frame1").ready( function() {
$("#frame1").contents().scrollTop( $("#frame1").contents().scrollTop() + 10 );
});
Run Code Online (Sandbox Code Playgroud)