问题
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