简体   繁体   English

在 Svelte 中使用 javascript 启用和禁用 div 元素

[英]enabling and disabling div element with javascript in Svelte

The following Svelte file produces a tree in which elements can be clicked.以下 Svelte 文件生成一个树,可以在其中单击元素。

Current behaviour当前行为

The problem I have is that when I click on the div-element, the element is focused, but the previous elements are not focused.我遇到的问题是,当我点击 div 元素时,该元素被聚焦,但之前的元素没有被聚焦。

Expected behaviour预期行为

Only one div is active at the same time.同时只有一个 div 处于活动状态。

Trials试炼

I've tried several re-writings of this code, but it seems like I need to keep track of some kind of history, to undo focus.我已经尝试多次重写这段代码,但似乎我需要跟踪某种历史,以撤消焦点。

<script lang="ts">
    import type { FrontendFile } from '$lib/front';
    export let content: FrontendFile;
    export let history: FrontendFile[];
    let text: string;
    function focusUnfocus() {
        for (let i=0; i++; i < history.length) {
            history[i].status.focused = false;
        }
        content.status.focused = !content.status.focused;
        history.push(content);

        if (content.status.focused) {
            text = 'font-black';
        } else {
            text = '';
        }
    }       


</script>
<div class="{text}" on:click={focusUnfocus}>
    {content.name}
</div>
...
{#each content.children as sub}
    <svelte:self bind:history bind:content={sub} />
{/each}
...

I solved it with the following我用以下方法解决了它

<script lang="ts">
    import type { FrontendFile } from '$lib/front';

    export let content: FrontendFile;
    export let lastFocused: FrontendFile;

    function focusUnfocus() {
        if (lastFocused) {
            lastFocused.status.focused = false;
        }
        content.status.focused = true;
        lastFocused = content;
    }

    let text: string = '';
    $: if (content.status.focused) {
        text = 'font-black';
    } else {
        text = '';
    }

</script>
<div class=" {text}" on:click={focusUnfocus}>
    {content.name}
</div>

{#each content.children as sub}
    <svelte:self bind:lastFocused bind:content={sub} />
{/each}

I switched to 1-object history and changed the binding in the top level index.svelte file as follows.我切换到 1-object history 并更改了顶级index.svelte文件中的绑定,如下所示。

<script lang="ts">
    export let lastFocused;
</script>
...
{#each filesystems as system}
    <RenderTree {lastFocused} bind:content={system}
{/each}
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM