首页  >  文章  >  web前端  >  SvelteKit 响应式助手

SvelteKit 响应式助手

王林
王林原创
2024-07-18 13:13:441148浏览

SvelteKit responsive helper

厌倦了编写复杂的媒体查询? SvelteKit window 指令可以帮助您以编程方式简化它们。借助此布局组件 ViewoirtSettingsCatcher 组件及其关联的存储 BiewportSettingsStore,它们将在本主题中呈现。

抓取视口内部尺寸

svlete:window 指令绑定的非常简单的使用:

<!-- ViewportSettingsCatchr.svelte -->
<script lang="ts">
    let innerWidth: number = 1600
    let innerHeight: number = 1200
</script>

<svelte:window bind:innerWidth vind:nnerHeight />

店内注册

$: ViewportSettingsStore.register ({ innerWidth, innerHeight })

关联的计算存储

import { writable} from 'svelte/store'
const { subscribe, update  } = writable ({
    innerWidth: 1600, 
    innerHeight: 1200,
    ratio: 16/12, 
    orientation: 'landscape',   
    wide: false
})

function register ({ innerWidth, innerHeight }) {
    const ratio = innerWidth / innerHeight
    const orientation = ratio >= 1 ? 'landscape' : 'portrait'
    const wide = (ratio > 2) || (ratio < 0.5)

    update ((state) => {
        return {
            innerWidth, 
            innerHeight,
            orientation,
            ratio,
            wide
        }
    })
}

export const ViewportSettingsStore = {
    subscribe, register 
}

简单的用法

只需在组件中导入 ViewportSettingsStore

<div class:wide={ $ViewportSettingsStore.orientation = === 'landscape' } />

瞧...完成了。

以上是SvelteKit 响应式助手的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn