Skip to main content

每一格块级别的元素都有 clientWidthclientHeightoffsetWidthoffsetHeight 这几个绑定:

App.svelte
<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>

这些绑定都是只读绑定,修改 wh 的值不会对元素造成任何影响。

Svelte 使用类似 这样 的方法获取元素的尺寸,这会涉及到一些开销,因此不建议在大量的元素上使用这个。

display: inline 的元素无法使用这种办法获取尺寸,不能包含其他元素的元素(比如 canvas)也不行。在这种情况下你需要先用一个包装元素把元素包起来再获取包装元素的尺寸。

Next: This

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
<script>
	let w;
	let h;
	let size = 42;
	let text = 'edit this text';
</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>{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>
 
initialising