我想問一個能弄清楚如何讓這個手風琴組件一次只打開一個部分的人。
這意味著如果一個新的手風琴打開,前一個手風琴必須自動關閉。
在理想情況下,此功能對于特定的手風琴是可選的。
感謝您的時間。
手風琴.svelte
<script>
import { linear } from 'svelte/easing';
import { slide} from 'svelte/transition';
export let open = false;
function handleClick() {
open = !open
}
</script>
<div class="accordion">
<div class="header" on:click={handleClick}>
<div class="text">
<slot name="head"></slot>
</div>
</div>
{#if open}
<div class="details" transition:slide="{{duration: 500, easing: linear}}" >
<slot name="details">
</slot>
</div>
{/if}
</div>
<style>
div.accordion {
margin: 1rem 0;
}
div.header {
display:flex;
width:100%;
}
div.header .text {
flex: 1;
}
div.details {
background-color: transparent;
padding:1rem;
}
</style>
應用程式.svelte
<script>
import Accordion from "./Accordion.svelte"
</script>
<Accordion>
<div slot="head">
<h2>Test one</h2>
</div>
<div slot="details">
<ul>
<Accordion>
<div slot="head">
<h4>The test of subitem?</h4>
</div>
<div slot="details">
<li>1</li>
<li>2</li>
<li>3</li>
</div>
</Accordion >
<Accordion>
<div slot="head">
<h4>Test of subitem 2</h4>
</div>
<div slot="details">
<li>one</li>
<li>two</li>
<li>three</li>
</div>
</Accordion>
</ul>
</div>
</Accordion>
<Accordion>
<div slot="head">
<h4>Second test</h4>
</div>
<div slot="details">
<ul>
<li>again one</li>
<li>two again</li>
<li>three repeat</li>
</ul>
</div>
</Accordion>
<style>
li {
margin: 0;
padding: 1em;
text-align: left;
list-style-type: none;
cursor: pointer;
color: black;
}
h4, h2 {
cursor: pointer;
}
</style>
uj5u.com熱心網友回復:
為此,通常會使用context。然后背景關系可以管理當前的手風琴(或代表它的鍵)或將事件分派到其他手風琴實體。
作為存盤當前手風琴的示例:
import { setContext, getContext } from 'svelte';
import { writable } from 'svelte/store';
const key = {}; // Object instances are unique, hence useful for keys
export const getAccordionContext = () => getContext(key);
export const createAccordionContext = () => {
const current = writable(null);
const context = { current };
setContext(key, context);
return context;
}
如果沒有與手風琴項結合使用的包裝器組件,則在別處(例如App)創建了一個背景關系。此外,每個手風琴項還應創建自己的背景關系,因此如果它包含自己的項,則在打開子項時不會關閉。
當打開手風琴時,可以更新背景關系的當前手風琴。反應式陳述句可用于關閉屬于背景關系的所有其他手風琴。
// In Accordion.svelte
const { current } = getAccordionContext();
const currentKey = {}; // Object representing current accordion component
createAccordionContext(); // Context for children
function handleClick() {
open = !open
if (open)
$current = currentKey;
}
$: if ($current != currentKey)
open = false;
REPL 示例
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/496035.html
標籤:javascript html 手风琴 苗条
