获取iframe中元素的Y位置

Get Y position of an element in an iframe

本文关键字:位置 元素 iframe 获取      更新时间:2024-05-26

我想这已经被问过了,我有一个iframe页面,我们有近10个文本字段,每当用户点击其中任何一个文本字段时,我都想知道该页面中的Y位置。这可能吗?

这是未经测试的,但应该为您指明正确的方向。

jQuery

   $(document).ready(function(){
      var iframe = $('iframe');
      var inputs = iframe.find('input');
      $.each(inputs, function(){
        $(this).click(function(){
          console.log($(this).offset().top));
        })
      })
    })

香草Javascript

根据评论更新。同样未经测试。

给你的iframe一个ID,使其更容易瞄准,然后:

var iframe = document.getElementById('iframe');
var inputs = Array.prototype.slice.call(iframe.getElementsByTagName('input'));
inputs.forEach(function(input,i){
  input.addEventListener('click', function(){
    console.log(this.getBoundingClientRect().top;
  })
})

如果主窗口和iframe内容都在同一协议/域内,则可以直接访问iframe的contentBody并获取输入字段的scrollTop位置。

例如:

var y = $('iframe').contents().find('#myInputField').offset().top;