Skip to main content
基本 Svelte
介绍
反应性
属性
逻辑
事件
绑定
类和样式
动作
转换
高级 Svelte
高级反应性
重用内容
运动
高级绑定
高级转换
上下文 API
特殊元素
<script module>
后续步骤
基本 SvelteKit
介绍
路由
加载数据
标题和 cookie
共享模块
表单
API 路由
$app/state
错误和重定向
高级 SvelteKit
钩子
页面选项
链接选项
高级路由
高级加载
环境变量
结论

你可以将 clientWidthclientHeightoffsetWidthoffsetHeight 绑定添加到任何元素,Svelte 将使用 ResizeObserver 更新绑定值:

¥You can add clientWidth, clientHeight, offsetWidth and offsetHeight bindings to any element, and Svelte will update the bound values using a 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>

这些绑定是只读的 - 更改 wh 的值不会对元素产生任何影响。

¥These bindings are readonly — changing the values of w and h won’t have any effect on the element.

display: inline 元素没有宽度或高度(具有 ‘intrinsic’ 尺寸的元素除外,如 <img><canvas>),并且无法通过 ResizeObserver 观察到。你需要将这些元素的 display 样式更改为其他样式,例如 inline-block

¥[!NOTE] display: inline elements do not have a width or height (except for elements with ‘intrinsic’ dimensions, like <img> and <canvas>), and cannot be observed with a ResizeObserver. You will need to change the display style of these elements to something else, such as 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>