1 回答

TA貢獻1946條經驗 獲得超4個贊
當您手動調整大小時,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>
- 1 回答
- 0 關注
- 101 瀏覽
添加回答
舉報