javascript - jquery 获取 iframe 中元素的 offset()

标签 javascript jquery iframe

我需要获取埋藏在 div 的 iframe 深处的提交按钮的偏移量信息。我想在加载 iframe 后将另一个元素放置在提交按钮旁边。 iframe 是从与包含页面相同的源加载的。

<div id="editBox">
  <iframe id="ifr" src="mysource">
      <html>
        <head></head>
          <body>
            <form id="dataForm" enctype="" method="POST" action="">
              <div>
                <table>  some form elements </table>
                <button id="submitButton" onclick="" type="submit">Save to file</button>

我已经尝试过

$('#editBox').contents().find('#submitButton').offset();

$('#ifr').contents().find('#submitButton').offset()

但两者都返回未定义。

我还将 .contents 语句包装在 setTimeout 中,以确定问题是否是我在加载 iframe 之前进行检查。 (如果这有效,我会添加一个加载的事件处理程序),但没有变化,结果仍然未定义。

如何获取我需要的位置信息?

最佳答案

将代码包装在 iframe 的 load() 函数中。这就像文档就绪函数或窗口加载函数一样工作:

$("#ifr").on("load", function(){
    var offset = $(this).contents().find('#submitButton').offset();
});

关于javascript - jquery 获取 iframe 中元素的 offset(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26619591/

相关文章:

javascript - Prototype.js 和数组中的类继承

javascript - Knockout - 如何引用单击的元素并传入参数

javascript - 突出显示 pre 标签中的内容...... AngularJS 方式?

javascript - 向全局对象添加属性

javascript - JQuery 事件应该更改 iframe 的 src

javascript - 使用 Jquery 以有限的间隔创建 DOM 元素

javascript - 第二个隐藏和显示带链接的 div

javascript - 调整 ng-repeat 过滤器的大小

javascript - 设置 iFrame CSS 显示 :none during load

javascript - 对于无渲染组件, enzyme 浅层返回未定义