如何将'offset'应用于iframe中的元素?

时间:2013-06-13 20:49:25

标签: javascript jquery iframe

我想从iframe外部的链接使用jQuery.animate导航到iframe中的div。 这是我使用的代码:

function scrollToAnchorIframe(aid){
  var aTag = window.frames['myFrame'].document.getElementById(aid);
  $('html,body').animate({scrollTop: aTag.offset().top - 62},'slow');
}

但是,它不起作用,记录错误“Object [object HTMLElement] has no method 'offset'”。有没有办法获得id的偏移量才能使它工作?

更新(已解决): 这就是我现在使用的代码:

function scrollToAnchorIframe(aid){
  var aTag = window.frames['myFrame'].document.getElementById(aid);
  jQuery('html,body').animate({scrollTop: $(aTag).offset().top + $("#myFrame").offset().top - 62},'slow');
}

2 个答案:

答案 0 :(得分:4)

aTag是DOM元素,使其成为jQuery对象

$('html,body').animate({scrollTop: $(aTag).offset().top - 62},'slow');

答案 1 :(得分:0)

如果将iframe放在容器框内,这里是一个更新,以便从父页面容器向上/向下导航到iframe的书签锚点(注意:“window.frames”与FF有已知的兼容性错误浏览器,所以我将改为使用“contentWindow”:

function iframeBookmark(anchor) {
mytag = document.getElementById("iframeID").contentWindow.document.getElementById(anchor);
pos1 = $(mytag).offset().top;
pos2 = $("#iframeID").offset().top;
if (pos2 > pos1) {
    $("#iframeContainerID").animate({scrollTop: pos2 - (pos2 - pos1) },'slow');
    }
else {
    $("#iframeContainerID").animate({scrollTop: pos2 + (pos1 - pos2)  },'slow');
    }
}

因此,当我们从父HTML调用该函数时,向上/向下滚动取决于iframe当前位置:

 <a onclick="iframeBookmark('iframeBookmarkID')">...</a>

...其中'iframeBookmarkID'是iframe页面中书签锚的ID。

相关问题