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

与过渡和动画一样,操作可以接受一个参数,操作函数将与其所属的元素一起调用。

¥Like transitions and animations, an action can take an argument, which the action function will be called with alongside the element it belongs to.

在这个练习中,我们想使用 Tippy.js 库向 <button> 添加工具提示。该操作已与 use:tooltip 连接,但如果你将鼠标悬停在按钮上(或使用键盘将其聚焦),工具提示将不包含任何内容。

¥In this exercise, we want to add a tooltip to the <button> using the Tippy.js library. The action is already wired up with use:tooltip, but if you hover over the button (or focus it with the keyboard) the tooltip contains no content.

首先,操作需要接受一个函数返回一些要传递给 Tippy 的选项:

¥First, the action needs to accept a function that returns some options to pass to Tippy:

App
function tooltip(node, fn) {
	$effect(() => {
		const tooltip = tippy(node, fn());

		return tooltip.destroy;
	});
}

我们传入一个函数,而不是选项本身,因为 tooltip 函数不会在选项更改时重新运行。

¥[!NOTE] We’re passing in a function, rather than the options themselves, because the tooltip function does not re-run when the options change.

然后,我们需要将选项传递到操作中:

¥Then, we need to pass the options into the action:

App
<button use:tooltip={() => ({ content })}>
	Hover me
</button>

在 Svelte 4 中,操作返回一个具有 updatedestroy 方法的对象。这仍然有效,但我们建议改用 $effect,因为它提供了更大的灵活性和粒度。

¥[!NOTE] In Svelte 4, actions returned an object with update and destroy methods. This still works but we recommend using $effect instead, as it provides more flexibility and granularity.

上一页 下一页
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
41
42
43
44
45
46
47
<script>
	import tippy from 'tippy.js';
 
	let content = $state('Hello!');
 
	function tooltip(node) {
		$effect(() => {
			const tooltip = tippy(node);
 
			return tooltip.destroy;
		});
	}
</script>
 
<input bind:value={content} />
 
<button use:tooltip>
	Hover me
</button>
 
<style>
	:global {
		[data-tippy-root] {
			--bg: #666;
			background-color: var(--bg);
			color: white;
			border-radius: 0.2rem;
			padding: 0.2rem 0.6rem;
			filter: drop-shadow(1px 1px 3px rgb(0 0 0 / 0.1));
 
			* {
				transition: none;
			}
		}
 
		[data-tippy-root]::before {
			--size: 0.4rem;
			content: '';
			position: absolute;
			left: calc(50% - var(--size));
			top: calc(-2 * var(--size) + 1px);
			border: var(--size) solid transparent;
			border-bottom-color: var(--bg);
		}
	}
</style>