Skip to main content
Svelte基础
介绍
响应
属性Props
逻辑表达式
事件
绑定
Classes和样式
动作Actions
转场
Svelte高阶
响应式进阶
内容复用
动画
高级绑定
高级转场
上下文API
特殊元素
脚本模块
接下来
SvelteKit基础
介绍
路由
加载数据
Headers和cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

Spring(弹簧) 类是 Tween(插值) 的替代方案,通常更适合处理频繁变化的值。 在此示例中,我们有一个跟随鼠标移动的圆,以及两个值——圆的坐标和大小。让我们将它们转换为弹簧:

The Spring class is an alternative to Tween that often works better for values that are frequently changing. In this example we have a circle that follows the mouse, and two values — the circle’s coordinates, and its size. Let’s convert them to springs:

App
<script>
	import { Spring } from 'svelte/motion';

	let coords = new Spring({ x: 50, y: 50 });
	let size = new Spring(10);
</script>
<script lang="ts">
	import { Spring } from 'svelte/motion';

	let coords = new Spring({ x: 50, y: 50 });
	let size = new Spring(10);
</script>

与 Tween 类似,弹簧具有一个可写的 target 属性和一个只读的 current 属性。更改事件处理程序:

As with Tween, springs have a writable target property and a readonly current property. Update the event handlers...

<svg
	onmousemove={(e) => {
		coords.target = { x: e.clientX, y: e.clientY };
	}}
	onmousedown={() => (size.target = 30)}
	onmouseup={() => (size.target = 10)}
	role="presentation"
>

更改<circle> 的属性:

...and the <circle> attributes:

<circle
	cx={coords.current.x}
	cy={coords.current.y}
	r={size.current}
></circle>

两个弹簧都使用默认的stiffness(硬度)damping(阻尼,衰减系数) 值,这些值控制弹簧的特性。我们可以指定自己的初始值:

Both springs have default stiffness and damping values, which control the spring’s, well... springiness. We can specify our own initial values:

App
let coords = new Spring({ x: 50, y: 50 }, {
	stiffness: 0.1,
	damping: 0.25
});

晃动你的鼠标,尝试拖动滑块,感受这些值如何影响弹簧的行为。注意,你可以在弹簧仍在运动时调整这些值。

Waggle your mouse around, and try dragging the sliders to get a feel for how they affect the spring’s behaviour. Notice that you can adjust the values while the spring is still in motion.

Edit this page on GitHub

<script>
let coords = $state({ x: 50, y: 50 });
let size = $state(10);
</script>

<svg
onmousemove={(e) => {
coords = { x: e.clientX, y: e.clientY };
}}
onmousedown={() => (size = 30)}
onmouseup={() => (size = 10)}
role="presentation"
>
<circle
cx={coords.x}
cy={coords.y}
r={size}
></circle>
</svg>

<div class="controls">
<label>
<h3>stiffness ({coords.stiffness})</h3>
<input
bind:value={coords.stiffness}
type="range"
min="0.01"
max="1"
step="0.01"
/>
</label>

<label>
<h3>damping ({coords.damping})</h3>
<input
bind:value={coords.damping}
loading Svelte compiler...
loading svelte compiler