SvelteKit:基于屏幕宽度设置不同方向的fly过渡效果
实现基于屏幕宽度的自适应fly过渡效果
可以通过监听媒体查询动态切换fly过渡参数,轻松实现需求,具体实现如下:
步骤1:添加响应式状态与屏幕监听
在脚本部分引入onMount,通过媒体查询跟踪屏幕尺寸变化,动态更新过渡参数:
<script lang="ts"> import { fade, fly } from 'svelte/transition'; import { onMount } from 'svelte'; /* Navigation menu */ const navigation = [ { title: 'Home', href: '/' }, { title: 'About', href: '/about' }, { title: 'Projects', href: '/projects' }, { title: 'Contact', href: '/contact' } ]; // 定义桌面端媒体查询规则 const desktopQuery = window.matchMedia('(min-width: 640px)'); // 初始化过渡参数 let flyOptions = desktopQuery.matches ? { x: -1000, duration: 300 } : { y: -1000, duration: 300 }; // 监听屏幕尺寸变化,实时更新过渡参数 onMount(() => { const handleScreenChange = (e: MediaQueryListEvent) => { flyOptions = e.matches ? { x: -1000, duration: 300 } : { y: -1000, duration: 300 }; }; desktopQuery.addEventListener('change', handleScreenChange); // 组件销毁时移除监听 return () => desktopQuery.removeEventListener('change', handleScreenChange); }); </script>
步骤2:绑定动态过渡参数到元素
将flyOptions直接绑定到in:fly和out:fly指令上即可:
<nav class="navigation" in:fade={{ duration: 100 }} out:fade={{ duration: 100 }}> <ul class="navigation__content" in:fly={flyOptions} out:fly={flyOptions} > {#each navigation as navItem} <li class="navigation__page"> <a href={navItem.href}>{navItem.title}</a> </li> {/each} </ul> </nav>
额外说明
- 使用
window.matchMedia监听媒体查询比监听resize事件更高效,仅在屏幕尺寸跨越640px阈值时触发更新 - 如果需要支持更多断点,可扩展媒体查询规则和对应的过渡参数
内容的提问来源于stack exchange,提问作者PuPpEt
相关产品推荐
相关产品推荐

