zl程序教程

您现在的位置是:首页 >  前端

当前栏目

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

jQuery 问题 修复 页面 失效 iframe 锚点
2023-06-13 09:15:44 时间

应用场景是:iframe页面没有滚动条,在父窗体中出现滚动条,锚点标记就会失效,因为,锚点是根据当前窗口滚动条滚动窗口的,成为子窗体后没有了滚动条,自然不会滚动。

解决办法是:用js判断页面是否被嵌套,用js计算iframe在父窗体位置,锚点在firame中的位置,两者相加成为父窗体的滚动。

遇到问题:获取父窗体元素(因为有域限制,所有需要在网络环境下方位(即http://domain.com));父窗体嵌套多个iframe,判断是否是当前iframe页面。

代码:

父窗体页面index.html

<!doctypehtml>
<html>
<head>
<title></title>
<styletype="text/css">
*{
margin:0;
padding:0;
border:0;
}
html,
body{
width:100%;
height:100%;
}
</style>
</head>
<body>
<divstyle="width:100%;background:#f00;height:500px;"></div>
<ahref="">dd</a>
<ahref="">ddd</a>
<iframename="iframe2"id="iframe2"src="iframe.html?a=b&c=d"style="width:100%;height:2060px;"></iframe>
<iframename="iframe2"id="iframe2"src="iframe.html?a=d&c=b"style="width:100%;height:2060px;"></iframe>
</body>
</html>

子窗体页面iframe.html

<!doctypehtml>
<html>
<head>
<title></title>
<styletype="text/css">
a{
padding:5px;
border:1pxsolid#f00;
float:left;
display:block;
margin-right:5px;
}
div{
width:80%;
margin:10pxauto;
height:500px;
border:1pxsolid#f00;
font-size:30px;
}
</style>
<scripttype="text/javascript"src="jquery-1.8.2.min.js"></script>
<scripttype="text/javascript">
$(function(){
//如果是iframe则需要在网络中访问,因为js里有域限制
//如果没有iframe则不进行处理,
if(window!==window.top){
//获取top窗口中的iframe,如果有iframe嵌套过多,请自行修改
variframeList=window.top.document.getElementsByTagName("iframe");
for(vari=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在父窗体的距顶部距离
vartop=window.top.document.getElementsByTagName("iframe")[i].offsetTop;
$("a").each(function(){
varhref=$(this).attr("href");
if(href.indexOf("#")!=-1){//判断是否是锚点而不是链接
varname=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>
<ahref="#a"rel="externalnofollow">a</a>
<ahref="#b"rel="externalnofollow">b</a>
<ahref="#c"rel="externalnofollow">c</a>
<ahref="#d"rel="externalnofollow">d</a>
<div><ahref=""name="rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"a">A</a></div>
<div><ahref=""name="rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"b">B</a></div>
<div><ahref=""name="rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"c">C</a></div>
<div><ahref=""name="rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"rel="externalnofollow"d">D</a></div>

</body>
</html>