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

就像你可以使用大括号来控制文本一样,你可以使用它们来控制元素属性。

¥Just like you can use curly braces to control text, you can use them to control element attributes.

我们的图片缺少 src — 让我们添加一个:

¥Our image is missing a src — let’s add one:

App
<img src={src} />

这样更好。但如果你将鼠标悬停在编辑器中的 <img> 上,Svelte 会向我们发出警告:

¥That’s better. But if you hover over the <img> in the editor, Svelte is giving us a warning:

`<img>` element should have an alt attribute

在构建 Web 应用时,重要的是确保它们可供尽可能广泛的用户群访问,包括(例如)视力或运动受损的人,或没有强大硬件或良好互联网连接的人。可访问性(缩写为 a11y)并不总是容易做到正确,但如果你编写了无法访问的标记,Svelte 会通过警告你来提供帮助。

¥When building web apps, it’s important to make sure that they’re accessible to the broadest possible userbase, including people with (for example) impaired vision or motion, or people without powerful hardware or good internet connections. Accessibility (shortened to a11y) isn’t always easy to get right, but Svelte will help by warning you if you write inaccessible markup.

在这种情况下,我们缺少描述图片的 alt 属性,供使用屏幕阅读器的人或网络连接缓慢或不稳定而无法下载图片的人使用。让我们添加一个:

¥In this case, we’re missing the alt attribute that describes the image for people using screenreaders, or people with slow or flaky internet connections that can’t download the image. Let’s add one:

App
<img src={src} alt="A man dances." />

我们可以在属性内使用大括号。尝试将其更改为 "{name} dances." — 记得在 <script> 块中声明一个 name 变量。

¥We can use curly braces inside attributes. Try changing it to "{name} dances." — remember to declare a name variable in the <script> block.

简写属性(Shorthand attributes)

¥Shorthand attributes

名称和值相同的属性并不罕见,例如 src={src}。Svelte 为我们提供了这些情况的便捷简写:

¥It’s not uncommon to have an attribute where the name and value are the same, like src={src}. Svelte gives us a convenient shorthand for these cases:

App
<img {src} alt="{name} dances." />
上一页 下一页
1
2
3
4
5
6
<script>
	let src = '/tutorial/image.gif';
</script>
 
<img />