在頁面中如何控制內嵌的iframe滾動呢?方法是使用iframe window的scroll方法,大家可以參考下面的示例
在頁面中如何控制內嵌的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>