1 回答

TA貢獻1804條經驗 獲得超7個贊
當您手動調整大小時,請element.style.{width, height}
設置好。因此,一種解決方案是自動調整大小以不使用這些屬性,而是以其他方式設置寬度和高度,以便您可以區分這些值。
對于width
,這很容易,因為自動調整大小僅設置height
: 如果width
設置(或者,如果您設置類似 的值calc(100% - 2px)
,則設置為其他值),斷開自動調整大小。
為了身高?這更難,但我想到了兩種技術:
在單獨的樣式表中設置高度(因此
element.style.height
根本不設置),并繼續更新該樣式元素的文本。使用
height: var(--height)
, 并設置--height
為實際值。除非用戶調整大小,否則這種方式element.style.height
不會改變。我推薦這種技術,因為它更容易推理,而且我懷疑它可能會快一點(盡管我根本沒有測試過)。
<style>
iframe {
width: calc(100% - 2px);
border: 1px solid black;
resize: both;
}
</style>
<iframe srcdoc="<h1>The quick brown fox jumps over the lazy doggerel."
style="height:var(--height)"
onload="
recalculate = () => {
// (var(--height) could just as easily be shifted to the stylesheet,
// but I’m demonstrating a point here in how it can be done.)
if (this.style.width || this.style.height !== 'var(--height)') {
// User resizing has occurred.
if (observer) {
observer.disconnect();
}
return;
}
this.style.setProperty('--height', this.contentDocument.documentElement.offsetHeight + 'px');
}
var observer = window.ResizeObserver && new ResizeObserver(recalculate);
if (observer) {
observer.observe(this.contentDocument.documentElement);
}
recalculate();
"></iframe>
添加回答
舉報