您可以將 clientWidth
、clientHeight
、offsetWidth
和 offsetHeight
綁定新增到任何元素,而 Svelte 將使用 ResizeObserver
更新綁定的值
App
<div bind:clientWidth={w} bind:clientHeight={h}>
<span style="font-size: {size}px" contenteditable>{text}</span>
<span class="size">{w} x {h}px</span>
</div>
這些綁定是唯讀的 — 更改 w
和 h
的值不會對元素產生任何影響。
display: inline
元素沒有寬度或高度(除了具有「內在」尺寸的元素,如<img>
和<canvas>
),並且無法使用ResizeObserver
觀察。您需要將這些元素的display
樣式變更為其他樣式,例如inline-block
。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<script>
let w = $state();
let h = $state();
let size = $state(42);
</script>
<label>
<input type="range" bind:value={size} min="10" max="100" />
font size ({size}px)
</label>
<div>
<span style="font-size: {size}px" contenteditable>
edit this text
</span>
<span class="size">{w} x {h}px</span>
</div>
<style>
div {
position: relative;
display: inline-block;
padding: 0.5rem;
background: hsla(15, 100%, 50%, 0.1);
border: 1px solid hsl(15, 100%, 50%);
}
.size {
position: absolute;
right: -1px;
bottom: -1.4em;
line-height: 1;
background: hsl(15, 100%, 50%);
color: white;
padding: 0.2em 0.5em;
white-space: pre;
}
</style>