SvelteKit 根据屏幕宽度显示组件的替代方式:

huangapple go评论62阅读模式
英文:

SvelteKit alternative way to display component base on screen width

问题

我在我的SvelteKit应用中使用这个来获取当前窗口大小,并在宽度较小时更改显示的组件:

```html
<script>
let size;
</script>
<svelte:window bind:innerwidth{size}/>
<div>
    {#if size > 768}
        <TableDisplay/>
    {:else}
        <CardsDisplay/>
    {/if}
</div>

还有其他方法可以实现这个吗?


<details>
<summary>英文:</summary>

I use this to get the current window size in my sveltekit app, and change the component being displayed when the width is small:

<script>
let size;
</script>
<svelte:window bind:innerwidth{size}/>
<div>
{#if size > 768}
<TableDisplay/>
{:else}
<CardsDisplay/>
{/if}
</div>


Is there any other way to do this?

</details>


# 答案1
**得分**: 1

[媒体查询][1] 是一种选择。

您可以定义类,根据视口宽度来显示/隐藏元素。这需要一个包装元素,样式可以应用于其中,或者您可以将规则定义为全局的,将类传递给组件并在组件中添加它们。

例如:

```svelte
<div class="show-large">
    <TableDisplay/>
</div>
<div class="show-small">
    <CardsDisplay/>
</div>

<style>
  /* `contents` 防止包装器影响布局 */
  .show-small { display: none; }
  .show-large { display: contents; }

  @media (max-width: 768px) {
    .show-small { display: contents; }
    .show-large { display: none; }
  }
</style>

REPL 示例

请注意,这与 {#if} 方法的行为不同:
使用媒体查询时,所有元素和组件都会被创建并插入文档中,只是不总是显示,而 {#if} 如果条件不满足则不创建任何内容。

英文:

Media queries would be an option.

You would define classes that show/hide an element depending on viewport width. This requires a wrapper element that the style can be applied to, or you define the rules as global, pass the class into the components and add them there.

E.g.

&lt;div class=&quot;show-large&quot;&gt;
    &lt;TableDisplay/&gt;
&lt;/div&gt;
&lt;div class=&quot;show-small&quot;&gt;
    &lt;CardsDisplay/&gt;
&lt;/div&gt;

&lt;style&gt;
  /* `contents` prevents wrapper from affecting layout */
  .show-small { display: none; }
  .show-large { display: contents; }

  @media (max-width: 768px) {
    .show-small { display: contents; }
    .show-large { display: none; }
  }
&lt;/style&gt;

REPL Example

Note that this does behave differently from the {#if} approach:
With media queries, all elements and components are created and inserted into the document, just not always shown, while {#if} does not create anything if the condition is not met.

huangapple
  • 本文由 发表于 2023年7月7日 06:42:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76632932.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定