jQuery 使用javascript上下滚动iframe

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1656665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:56:38  来源:igfitidea点击:

Using javascript to scroll iframe up and down

jqueryiframekey

提问by Mickey Cheong

Is it possible to scroll the iframe window from the parent window using keys or javascript? The iframe content is from another domain, different from the parent window.

是否可以使用键或 javascript 从父窗口滚动 iframe 窗口?iframe 内容来自另一个域,与父窗口不同。

回答by Martin Nycander

Since the iframe content is from another domain, you will not be able to alter it's DOM due to security reasons.

由于 iframe 内容来自另一个域,出于安全原因,您将无法更改它的 DOM。

Although you can scroll it by using the arrow keys, when you have it activated. At least it works for me in Chrome and Firefox.

虽然您可以使用箭头键滚动它,但当您激活它时。至少它在 Chrome 和 Firefox 中对我有用。

If you want to be able to scroll it from javascript, I would suggest the following approach. (it assumes you know the width and height of the iframe content and your iframe). Basically let a div in your DOM take care of scrolling.

如果您希望能够从 javascript 滚动它,我建议采用以下方法。(它假设您知道 iframe 内容和 iframe 的宽度和高度)。基本上让 DOM 中的 div 负责滚动。

<a href="#" id="scroll">Scroll to (400,400)!</a><br />

<div id="google" style="width: 300px; height: 200px; overflow: auto;">
   <iframe width="800" height="600" src="http://www.google.com/" scrolling="no">
   </iframe>
</div>

<script type="text/javascript">
$("#scroll").click(function()
{
  $("#google").scrollTop(400).scrollLeft(400);
  return false;
});
</script>

For smoother scrolling of the div you could try the code from this article.

为了更流畅地滚动 div,您可以尝试使用本文中的代码。