需求場景:
- 父頁面A 包含有iframe頁面B,
- 頁面B內容很長,瀏覽器一兩屏不能顯示全。
- B頁面相關內容在網頁最前端有目錄連接list1, list2, 點擊list1或者list2瀏覽器向下滾動到content1或者content2處。即需要在同頁面中使用錨點連接機制
解決思路:
- iframe子頁面中的目錄連接點擊之后將相關高度傳給top窗口
- 由top窗口更改document的scrollTop屬性,實現頁面滾動到響應位置
實現:
iframe 頁面內的相關代碼如下:
setWindowScrollTop 中高度加100是父頁面與iframe B頁面頂部的間距
<ul> <li><a href="javascript: setWindowScrollTop (top,document.getElementById('id_content1').offsetTop+ 100);"><strong>1</strong> list1</a></li> <li><a href="javascript: setWindowScrollTop (top,document.getElementById('id_content2').offsetTop+ 100);"><strong>2</strong> list2</a></li> </ul> ……. <div id="id_content1">1 content1</div> <div id="id_content2">2 content2</div>
|
相關js代碼:
function setWindowScrollTop(win, topHeight)
{
if(win.document.documentElement)
{
win.document.documentElement.scrollTop = topHeight;
}
if(win.document.body){
win.document.body.scrollTop = topHeight;
}
}
附:普通頁面的錨點問題:
該問題網上已經有很多討論了,總的來說錨點的實現基於瀏覽器對url中#name 的支持。且與標簽<a>有緊密關系
<a href="#Content1">list1</a>
<a href="#Content2">list2</a>
…
<a name=" Content1" id=" Content1"></a>
Content1…
<a name=" Content1" id=" Content1"></a>
Content1…