【问题标题】:jquery resize parent childjquery调整父子大小
【发布时间】:2011-02-06 02:02:32
【问题描述】:

我有一个带有类嵌入和唯一 ID 的 div 容器。在容器 div 内,我有一个使用 iframe 或对象的嵌入式播放器代码。例如:

<div class="embed" id"id21" style="width:480px; height:390px;">
<iframe width="480" height="390" src="http://www.youtube.com/embed/Oe_3KgfcCXs" frameborder="0" allowfullscreen></iframe>
</div>

当我调整 div 容器的大小时,我希望其中的播放器也调整大小。嵌入代码具有宽度和高度的属性。我做了以下但无法让它工作。我需要通过它的 id 来引用容器,所以如果我有另一个具有不同 id 的容器,调整大小应该只对正在调整大小的容器生效,而不是对其他容器生效。

$('.embed').live({
    resize: function(event, ui) {
        var id = this.id;
        var height = $(id).height();
        var width = $(id).width();
        $(id).contents().attr({'width':width,'height':height});
    }
});

【问题讨论】:

    标签: jquery resize


    【解决方案1】:
    $('.embed').live({
        resize: function(event, ui) {
            $(this).find("iframe").css(ui.size);
        }
    });
    

    这不行吗?

    【讨论】:

    • 很好的单行答案。但是如果播放器是使用对象而不是 iframe 嵌入的呢?我们需要检查 iframe 和对象。
    • 然后使用逗号分隔,.find("iframe,whateverdomelement")
    • ... 如果.embed 元素中只有一个子元素,则只需children()
    • 是的,你是对的 Šime,但我喜欢控制我所控制的 :)
    【解决方案2】:

    如果您使用 CSS 来控制iframe 的height 和width 的相对尺寸,比如%,那么调整div 的大小将自动调整iframe 的大小:

    iframe {
        height: 80%;
        width: 100%;
        margin: 0 auto;
    }
    

    这仅在.embed 具有如您的示例中定义的尺寸时才有效。


    编辑修改html、css并提供演示jQuery:

    html:

    <div class="embed" id="id21" style="width:480px; height:390px;">
        <iframe src="http://www.youtube.com/embed/Oe_3KgfcCXs" frameborder="0" allowfullscreen></iframe>
    </div>
    

    css

    .embed {
        border: 5px solid #000;
        padding: 1em;
    }
    
    .embed:hover {
        border-color: #f90;
    }
    
    iframe {
        width: 100%;
        height: 100%;
        margin: 0 auto;
    }
    

    jQuery:

    $('.embed').resizable(
        {
            aspectRatio: 1.23,
            minHeight: 390,
            minWidth: 480
         });
    

    JS Fiddle demo.

    【讨论】:

    • 好主意。为此+1。您的方式意味着我还必须将默认 iframe 宽度高度更改为 100% 才能工作。这意味着更多的代码。 Youtube 默认为 480x390。
    【解决方案3】:

    试试这个:

    $('.embed').live({
        resize: function(event, ui) {
            $(this).children()
                .width( $(this).width() )
                .height( $(this).height() );
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-14
      • 1970-01-01
      • 2012-12-02
      • 1970-01-01
      • 2014-12-29
      相关资源
      最近更新 更多