Posted in Javascript onMarch 05, 2014
在页面中如何控制内嵌的iframe滚动呢?方法是使用iframe window的scroll方法:
1、获取iframe的窗口对象
var iwin = document.getElementById('iframe1').contentWindow;
2 、获取iframe的窗口document对象
var doc = iwin.document;
3、调用iframe window对象的scroll方法
iwin.scroll(0,doc.body.scrollHeight);
scroll两个参数为x,y轴的滚动量
doc.body.scrollHeight为iframe页面的高度(包含未显示的部分)
一个综合应用例子如下:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title>hover test</title> <style type="text/css"> ul{ background-color:#ff00ff; display:block; } .toc li{ position:relative; width:10em; background-color:#00ff00; display:block; } li a { /*display:block;*/ /*若以块的模式显示,则会占满整个父元素空间*/ background-color:#0000ff; } /*必须让a成为块级元素*/ li a i{ display:none; } li a:hover{ text-align:left; }/*这里添加的代码只是为了让IE6显示,没有特殊功能,除text-decoration,color,z-index外都可以写*/ .toc li a:hover i{ display:block; width:6em; position:absolute; top:0; left:100%; /* 这里100%指相对于元素li的宽度*/ margin:-1em 0 0 0em; padding:1em; background:#cde; border:1px solid red; text-align:left; z-index:10000; } </style> </head> <body> <iframe id="iframe1" src="" width="400" height="300"></iframe> html代码 <ul class="toc" id="toc"> <li><a href="1.html">Chapter 1<i>In which a dragon is seen</i></a></li> <li><a href="2.html">Chapter 1<i>In which a knight is summoned</i></a></li> <li><a href="3.html">Chapter 1<i>In which a proncess is disappointed</i></a></li> <li><a href="4.html">Chapter 1<i>In which a dragon is seen</i></a></li> <li><a href="5.html">Chapter 1<i>In which a dragon is seen</i></a></li> <li><a href="6.html">Chapter 1<i>In which a dragon is seen</i></a></li> <li><a href="7.html">Chapter 1<i>In which a dragon is seen</i></a></li> </ul> <script language="javascript"> function getElementAbsPos(e) { var t = e.offsetTop; var l = e.offsetLeft; while(e = e.offsetParent) { t += e.offsetTop; l += e.offsetLeft; } return {left:l,top:t}; } function getPosition(obj){ var left = 0; var top = 0; while(obj != document.body){ left = obj.offsetLeft; top = obj.offsetTop; obj = obj.offsetParent; } return left; } var lis = document.getElementsByTagName('li'); var iwin = document.getElementById('iframe1').contentWindow; var doc = iwin.document; for(var i=0;i<lis.length;i++){ lis[i].onmouseover = function(){ var obji = this.childNodes[0].childNodes[1]; doc.writeln('<br>'+ obji.innerText + ',' + getElementAbsPos(document.getElementById('toc')).left); doc.writeln('<br>'+ obji.offsetLeft + ',' + getElementAbsPos(obji).left + ',' + obji.offsetWidth+ ',' + obji.style.left); doc.writeln('<br><b>'+ doc.body.scrollHeight + '</b>') iwin.scroll(0,doc.body.scrollHeight); //iwin.scrollTo(10000); //无效 } } </script> </body> </html>
使用iframe window的scroll方法控制iframe页面滚动
声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@