用jquery修复在iframe下的页面锚点失效问题


应用场景是: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++){
//判断当前窗口是否循环中的iframe
if(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>

« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3