我编写了一个脚本来根据 iframe 的高度调整页面的高度(从 iframe 内)。我添加了触发的事件:
该脚本在我的设备上运行 - Windows 10、Chrome,但我仍然收到报告说它在软刷新上不起作用。
这是代码。我知道这很可怕:
// Don't fire on height resizing
$h = 0;
$first_keyup_complete = false;
$set_height_on_scroll = false;
$(function () {
$(window).load(function(){
$h = $( window ).height();
setTimeout(function(){ setHeight(); }, 1000);
setTimeout(function(){ setHeight(); }, 2000);
setTimeout(function(){ setHeight(); }, 3000);
});
});
$("#lfform-placeholder iframe").click( function (e) {
if (!$first_keyup_complete) {
setHeight();
$first_keyup_complete = true;
}
});
$("#lfform-placeholder iframe").scroll( function (e) {
if (!$set_height_on_scroll) {
setHeight();
$set_height_on_scroll = true;
}
});
$( window ).resize( function(){
if( $h != $( window ).height() ){
$h = $( window ).height();
} else {
setHeight();
}
});
$('.btn2, .btn1, .progress-bar__section.active, .toggle-btn').click(function(){
setTimeout(function(){ setHeight(); }, 1000);
});
function setHeight() {
parent.postMessage({ if_height: $('body').outerHeight( true ) }, 'https://example.com/' );
};
这是接受帖子消息并相应调整页面高度的脚本:
window.addEventListener('load', function(){
$iframe_height = 0;
$iframe = document.getElementById('lf-frame-374417');
window.addEventListener('message', function(e) {
if (e.data.if_height != undefined) {
$height = Number( e.data.if_height ) + 30; // add 30px to accomodate box shadow on form
$iframe.setAttribute( 'style', 'height: ' + $height + 'px !important;');
}
});
});
有谁知道如何根据 iframe 的高度可靠地调整父页面的高度?我觉得我什么都试过了。它们不是同源的,并且 iframe 的高度是可变的(它是一个包含许多页面/手风琴的表单)。我可以访问 iframe 和父级。