插件窝 干货文章 SvelteKit 响应式助手

SvelteKit 响应式助手

innerwidth class innerheight viewportsettings 383    来源:    2024-10-23

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

抓取视口内部尺寸

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

<!-- viewportsettingscatchr.svelte -->
<script lang="ts">
    let innerwidth: number = 1600
    let innerheight: number = 1200
</script><window bind:innerwidth vind:nnerheight></window>

店内注册

$: 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 &gt;= 1 ? 'landscape' : 'portrait'
    const wide = (ratio &gt; 2) || (ratio  {
        return {
            innerwidth, 
            innerheight,
            orientation,
            ratio,
            wide
        }
    })
}

export const viewportsettingsstore = {
    subscribe, register 
}

简单的用法

只需在你的组件中导入 viewportsettingsstore

<div class:wide="{"></div>

et voilà...完成了。