英文:
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>
请注意,这与 {#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.
<div class="show-large">
<TableDisplay/>
</div>
<div class="show-small">
<CardsDisplay/>
</div>
<style>
/* `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; }
}
</style>
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论