eastpoint

イベント

"on:{...}"にてHTML要素にイベントハンドラを設定する。

app.svelte
<script>
        import Event from './Event.svelte';
</script>

<main>
        <Event />
</main>

<style>
</style>
Event.svelte
<script>
        const messages = ['ON', 'OFF'];
        let current = 0;
        const toggle = () => current = (current+1) % 2;

        let m = { x: 0, y: 0 };

        function moveMouse(event) {
                m.x = event.clientX;
                m.y = event.clientY;
        }

        let msg = "";
        function pressKey(event) {
                msg = msg + " 0x" + event.keyCode.toString(16);
        }

</script>

<lavel>click</lavel>
<li><button on:click={toggle}>{messages[current]}</button></li>

<lavel>mousemove</lavel>
<div on:mousemove={moveMouse}>
        mouse position: {m.x} x {m.y}
</div>

<lavel>keyboard</lavel>
<textarea on:keypress={pressKey}></textarea>
<p>{msg}</p>

<style>
        lavel {display:block; margin-top: 1em}
        li {list-style:none; margin-left:2em}
        div {width: 220px; height: 220px; border:solid 1px; margin-left:2em}
        textarea {margin-left:2em}
</style>

適用イメージ