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

就像在先前练习中见过的,我们可以通过使用on<name>形式的函数监听Dom元素的事件(例如:单击事件,指针移动事件

As we’ve briefly seen already, you can listen to any DOM event on an element (such as click or pointermove) with an on<name> function:

App
<div onpointermove={onpointermove}>
	The pointer is at {Math.round(m.x)} x {Math.round(m.y)}
</div>

跟其它属性一样,如果属性和值名称一样我们就可以使用简写形式:

Like with any other property where the name matches the value, we can use the short form:

App
<div {onpointermove}>
	The pointer is at {Math.round(m.x)} x {Math.round(m.y)}
</div>

Edit this page on GitHub

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<script>
	let m = $state({ x: 0, y: 0 });
 
	function onpointermove(event) {
		m.x = event.clientX;
		m.y = event.clientY;
	}
</script>
 
<div>
	The pointer is at {Math.round(m.x)} x {Math.round(m.y)}
</div>
 
<style>
	div {
		position: fixed;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		padding: 1rem;
	}
</style>