【问题标题】:Adapt 100 percent height to javascript widget使 100% 高度适应 javascript 小部件
【发布时间】:2013-05-29 06:54:45
【问题描述】:

我已经上下搜索了,但我一直无法找到允许我使用以下代码调整页面高度的答案:

// Set path to the iframe file
var filePath = 'http://www.mysite.com/widget/widget.php';
// Setup the iframe target
var iframe='<iframe id="frame" name="widget" src ="http://www.mysite.com/widget/widget.php" width="100%" height="100%" marginheight="0" marginwidth="0" frameborder="no" scrolling="no"></iframe>';
// Write the iframe to the page
document.write(iframe);

var myIframe = parent.document.getElementById("frame");
// Setup the width and height
myIframe.height = 450;
myIframe.width = 255;

myIframe.src = filePath;
// set the style of the iframe
myIframe.style.border = "1px solid #dddddd";
myIframe.style.padding = "2px";

请注意“myIframe.height = 450;”将我的小部件限制为 450 像素高...我需要它来允许我的小部件调整为 100%,是的,我尝试了“100%”但它不起作用。

当我将此代码放在创建简单小部件的站点上时,会提取上面的代码。

这里是原始 javascript iframe 小部件的来源:http://papermashup.com/creating-an-iframe-with-javascript/ 但他们没有关于如何拥有 100% 高度的说明

【问题讨论】:

  • 您可以使用CSS:position: absolute/fixed并设置top+bottom: 0
  • @Teemu 会作为样式直接添加到 iframe 中吗?
  • 测试一下。如果它不起作用,请将该 CSS 用于包装器 div100% 用于 iframe
  • @Teemu 感谢您的帮助,但都不管用。
  • 没有?也许是document.write()。检查这个Fiddle

标签: javascript iframe widget


【解决方案1】:

这对我有用。诀窍是获取页面可见区域的高度,而不仅仅是高度:这是因为主体高度跟随其自身内部的内容,如果你有一个固定的元素高度,主体高度不会变小而是变大

$(window).resize(function () {
    //frame height
    var f = $('#frame').height();
    //window visible height <-- height css(height) and other works for the real height, not just the visible
    var h = window.innerHeight; 
    //give some pixel less to let the iframe fit the screen
    var something = 5;
    //if h is less then 450, resize the iframe 
    if (h < 450 ){
        $('#frame').height(h- something);
        console.log($('#frame').css('height'));
    }else{
        //else, if the iframe height is less then 450, make it bigger
        if(f<450){
            $('#frame').height('450');
        }   
    }
});

无论如何,如@timo所示,最好避免document.write

【讨论】:

    猜你喜欢
    • 2011-04-29
    • 2015-12-07
    • 1970-01-01
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多