如何使用javascript滚动到iframe中的特定位置

时间:2016-12-23 16:30:50

标签: javascript html iframe

我有一个页面A.html,通过iframe嵌入页面B.html。

A.html

<Html>
  <Head>
   <Title> A.html </title>
  </Head>
  <Body>
   <Iframe name = "myframe" id = "myframe" src = "B.html" frameborder = "0"/> 
 </Body>
</Html>

B.html

<Html>
 <Head>
  <Title> B.html </title>
   <Style type = "text/css" media = "screen">
    .body {margin: 0px 0px 0px 0px; font-size: medium;}
  </Style>
 </Head>
  <Body class = "body">
    <Table  width = "100%" height = "100%" align = "left" cellspacing = "0" cellpadding = "0">
      .
      .
   </Table>
   <Table  width = "100%" height = "100%" align = "left" cellspacing = "0" cellpadding = "0">
      The content I want to display!
   </Table>
   <Table  width = "100%" height = "100%" align = "left" cellspacing = "0" cellpadding = "0">
     .
     .
   </Table>
   </Body>
   </Html>

我想在A.html中显示B.html的table2内容,我发现了一些方法,比如

 var myIframe = document.getElementById('myframe');
  myIframe.onload = function(){
      myIframe.contentWindow.scrollTo(100,500);
  };

但B.html页面大小未设置,三个表 height =“100%”,B.html显示为百分比页面,它在浏览器中滚动到三个页面。  所以 scrollTo(x,y)方法不起作用,有没有好办法? 非常感谢你!

1 个答案:

答案 0 :(得分:0)

您可以滚动到任何设置了ID的HTML元素的位置。

因此,如果有一个表格<a href="#my-table">go to table</a>,您可以使用锚点链接转到它 #my-table

iframe中的内容也是如此 将您的来源设置为您想要的网址,并在结尾处添加#footer(或类似的内容)。

在下面的代码段中,我使用了一个直接指向Stackoverflow.com主页的.myframe { height: 320px; width: 480px; }的iframe。

<iframe class="myframe" src="http://www.stackoverflow.com#footer"></iframe>
def contact(request):
    if request.method == 'POST':
    form = ContactForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            client = twilio.rest.TwilioRestClient('xx...', 'xxx...')
            recipients = employees.objects.filter(group__contains='admin')
            for number in recipients:
                client.messages.create(body='Sample text',to=number, from_='xxxxxx')

            return HttpResponseRedirect('/contact/thanks/')
    else:
        form = ContactForm()
    return render(request, 'contact_form.html', {'form':form})