CSS frame-sizing让iframe基于内容高度自适应实例页面

回到相关文章 »

效果:

代码:

CSS代码:
/* textarea 随内容高度自增 */
.editor {
    width: 100%;
    box-sizing: border-box;
    min-height: 62px;
    padding: 8px 10px;
    font: 14px/1.6 system-ui, sans-serif;
    resize: vertical;
    field-sizing: content;
}

/* iframe:不支持时保留固定高度作为降级 */
.comments-frame {
    width: 100%;
    height: 120px;
    border: 1px solid #d0d0d5;
}

/* 支持时高度由浏览器按嵌入文档内容计算 */
@supports (frame-sizing: content-height) {
    .comments-frame {
        height: auto;
        frame-sizing: content-height;
    }
}
HTML代码:
<textarea class="editor" id="editor"></textarea>
<button id="send" type="button">发送给 iframe</button>
<iframe class="comments-frame" id="comments" src="comment.html" title="评论列表"></iframe>

<!-- comment.html 中必须静态声明,不能后续用 JS 添加 -->
<meta name="responsive-embedded-sizing" content="allow-origins=*">
                
JS代码:
const editor = document.getElementById("editor");
const frame = document.getElementById("comments");
const sendBtn = document.getElementById("send");

// 把评论内容发送给嵌入文档
sendBtn.addEventListener("click", function () {
    const text = editor.value.trim();
    if (text == "") {
        return;
    }
    frame.contentWindow.postMessage({
        type: "comment",
        text: text
    }, location.origin);
    editor.value = "";
    editor.focus();
});

// 不支持 frame-sizing 时的兼容方案:由 iframe 上报高度
if (CSS.supports("frame-sizing", "content-height") == false) {
    document.getElementById("unsupported").hidden = false;
    window.addEventListener("message", function (event) {
        if (event.origin !== location.origin || event.source !== frame.contentWindow) {
            return;
        }
        if (event.data && event.data.type === "iframe-height") {
            frame.style.height = event.data.height + "px";
        }
    });
}