用jquery修複在iframe下的頁面錨點失效問題,jqueryiframe
應用情境是:iframe頁面沒有捲軸,在父表單中出現捲軸,錨點標記就會失效,因為,錨點是根據當前視窗捲軸滾動視窗的,成為子表單後沒有了捲軸,自然不會滾動。
解決辦法是:用js判斷頁面是否被嵌套,用js計算iframe在父表單位置,錨點在firame中的位置,兩者相加成為父表單的滾動。
遇到問題:擷取父表單元素(因為有域限制,所有需要在網路環境下方位(即http://domain.com));父表單嵌套多個iframe,判斷是否是當前iframe頁面。
代碼:
父表單頁面 index.html
<!doctype html><html><head><title></title><style type="text/css">*{margin: 0;padding: 0;border: 0;}html,body{width: 100%;height: 100%;}</style></head><body><div style="width:100%;background:#f00;height:500px;"></div><a href="">dd</a><a href="">ddd</a><iframe name="iframe2" id="iframe2" src="iframe.html?a=b&c=d" style="width:100%;height:2060px;"></iframe><iframe name="iframe2" id="iframe2" src="iframe.html?a=d&c=b" style="width:100%;height:2060px;"></iframe></body></html>
子表單頁面iframe.html
<!doctype html><html><head><title></title><style type="text/css">a{padding: 5px;border: 1px solid #f00;float: left;display: block;margin-right: 5px;}div{width: 80%;margin: 10px auto;height: 500px;border: 1px solid #f00;font-size: 30px;}</style><script type="text/javascript" src="jquery-1.8.2.min.js"></script><script type="text/javascript">$(function(){//如果是iframe則需要在網路中訪問,因為js裡有域限制//如果沒有iframe則不進行處理,if(window!==window.top){//擷取top視窗中的iframe,如果有iframe嵌套過多,請自行修改var iframeList=window.top.document.getElementsByTagName('iframe');for(var i=0;i<iframeList.length;i++){//判斷當前視窗是否迴圈中的iframeif(window.location.toString().indexOf(iframeList[i].getAttribute('src').toString())!=-1){//等自己的所在iframe載入完成給a錨點加事件window.top.document.getElementsByTagName('iframe')[i].onload=function(){//確定iframe在父表單的距頂部距離var top = window.top.document.getElementsByTagName('iframe')[i].offsetTop;$('a').each(function(){var href = $(this).attr('href');if(href.indexOf('#')!=-1){//判斷是否是錨點而不是連結var name = href.substring(href.indexOf('#')+1);$(this).bind('click',function(){$('a').each(function(){if($(this).attr('name')==name){//父視窗滾動$(window.parent).scrollTop($(this).offset().top+top);}});});}});}}}}});</script></head><body><a href="#a" rel="external nofollow" >a</a><a href="#b" rel="external nofollow" >b</a><a href="#c" rel="external nofollow" >c</a><a href="#d" rel="external nofollow" >d</a><div><a href="" name=" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" a">A</a></div><div><a href="" name=" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" b">B</a></div><div><a href="" name=" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" c">C</a></div><div><a href="" name=" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" d">D</a></div></body></html>
教父頁控制iframe中錨點
要給iframe一個name屬性:
譬如1.htm裡面是<iframe name="iframe1" src="2.htm"></iframe>
那麼1.htm裡面的連結就是<a href="2.htm#a" target="iframe1">A</a>
Firefox錨點跳轉在iframe下不起作用,是怎解決的?我也有這個問題
說來話長,總體來說就是ie和Firefox對iframe的實現略有區別