Get Y position of an element in an iframe

旧巷老猫 提交于 2021-01-29 02:38:25

问题


I think this has been asked already, I have an iframe page where we have nearly 10 textfield's, whenever the user taps on any one of the textfield, I would like to know the Y position in that page. Is that possible?


回答1:


This is untested, but should point you in the right direction.

jQuery

   $(document).ready(function(){
      var iframe = $('iframe');
      var inputs = iframe.find('input');

      $.each(inputs, function(){
        $(this).click(function(){
          console.log($(this).offset().top));
        })
      })
    })

Vanilla Javascript

Updated as per comment. Also untested.

Give your iframe an ID to make it easier to target, then:

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;
  })
})



回答2:


If both, the main window and the iframe content are within the same protocol/domain, then you can directly access the iframe's contentBody and get the scrollTop position of the input field.

For instance:

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


来源:https://stackoverflow.com/questions/36578744/get-y-position-of-an-element-in-an-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!