Svelte <svelte:window>
2023-02-22 16:06 更新
如同事件可以监听 DOM 标签一样,你可以通过window
对象给 <svelte:window>
标签添加事件监听:
在代码第33行,添加 keydown
监听事件:
<svelte:window on:keydown={handleKeydown}/>
与DOM标签一样,您可以添加 事件修饰符 ,例如
preventDefault
。
示例代码
- App.svelte
<script>
let key;
let keyCode;
function handleKeydown(event) {
key = event.key;
keyCode = event.keyCode;
}
</script>
<style>
div {
display: flex;
height: 100%;
align-items: center;
justify-content: center;
flex-direction: column;
}
kbd {
background-color: #eee;
border-radius: 4px;
font-size: 6em;
padding: 0.2em 0.5em;
border-top: 5px solid rgba(255,255,255,0.5);
border-left: 5px solid rgba(255,255,255,0.5);
border-right: 5px solid rgba(0,0,0,0.2);
border-bottom: 5px solid rgba(0,0,0,0.2);
color: #555;
}
</style>
<svelte:window on:keydown={handleKeydown}/>
<div style="text-align: center">
{#if key}
<kbd>{key === ' ' ? 'Space' : key}</kbd>
<p>{keyCode}</p>
{:else}
<p>Focus this window and press any key</p>
{/if}
</div>
以上内容是否对您有帮助:
更多建议: