我使用 JavaScript 动态加载 iframe。加载后,如何让它向下滚动特定数量的像素(即在 iframe 中的页面加载后,如何让 iframe 自行滚动到页面的指定区域?)
使用 JavaScript 滚动 iframe?
IT技术
javascript
iframe
scroll
2021-02-08 10:21:23
6个回答
受到纳尔逊评论的启发,我做了这个。
关于在源自外部域的文档上使用.ScrollTo() 的 javascript 同源策略的解决方法。
非常简单的解决方法是创建一个虚拟 HTML 页面,在其中托管外部网站,然后在加载后在该页面上调用 .ScrollTo(x,y)。然后你唯一需要做的就是有一个框架或 iframe 来打开这个网站。
还有很多其他方法可以做到这一点,这是迄今为止最简单的方法。
*注意高度必须大以容纳滚动条最大值。
--home.html
<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>
--weather.html
<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>
受Nelson和Chris评论的启发,我找到了一种使用 adiv
和 an解决同源策略的方法iframe
:
HTML:
<div id='div_iframe'><iframe id='frame' src='...'></iframe></div>
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 */
}
现在假设我想通过滚动到该位置来跳过 iframe 页面的前 438 个(垂直)像素。
JS解决方案:
document.getElementById('div_iframe').scrollTop = 438
jQuery 解决方案:
$('#div_iframe').scrollTop(438)
CSS 解决方案:
#frame { margin-top: -438px }
(单独每个解决方案就足够了,CSS 的效果有点不同,因为您无法向上滚动以查看 iframe 页面的顶部。)
使用scrollTop
框架内容的属性将内容的垂直滚动偏移设置为特定数量的像素(如 100):
<iframe src="foo.html" onload="this.contentWindow.document.documentElement.scrollTop=100"></iframe>
一个 jQuery 解决方案:
$("#frame1").ready( function() {
$("#frame1").contents().scrollTop( $("#frame1").contents().scrollTop() + 10 );
});
其它你可能感兴趣的问题