【问题标题】:Misconception regarding svelte transitions关于苗条过渡的误解
【发布时间】:2022-08-03 21:23:19
【问题描述】:

我尝试在这里使用此 repl (https://svelte.dev/tutorial/in-and-out) 的帮助来使一些 div 飞入和淡出。然而我觉得我脑子里有点误会......

我创建了一个如下所示的组件:

<script>
  import { fade, fly } from \"svelte/transition\";

  let steps = [
    { text: \"these\" },
    { text: \"are\" },
    { text: \"the\" },
    { text: \"instructions\" },
  ];

  function showNext() {
    if (currentStep === steps.length - 1) {
      return;
    }
    currentStep++;
  }

  function showPrev() {
    if (currentStep === 0) {
      return;
    }
    currentStep--;
  }


</script>

<div
  class=\"h-36 flex items-center justify-center text-xl w-32 mx-auto\"
  in:fly={{ y: 200, duration: 2000 }}
  out:fade
>
  {steps[currentStep].text}
</div>

<button on:click={showPrev}>Back</button>
<button on:click={showNext}>Next</button>

每次单击 Back 或 NextButton 时,我都想飞入并淡出 div 的内容。但它不会飞入也不会淡出。我想这只是因为我正在更改 div 中的 html 内容,对吧?如果是这样,什么是飞入和淡出 steps 中每个对象的好选择?

    标签: javascript svelte


    【解决方案1】:

    转换在元素创建/销毁时触发。要完成这项工作,您可以在带有过渡的元素周围使用{#key}。

    {#key currentStep}
        <div
            class="h-36 flex items-center justify-center text-xl w-32 mx-auto"
            in:fly={{ y: 200, duration: 2000 }}
            out:fade
        >
            {steps[currentStep].text}
        </div>
    {/key}
    

    REPL

    请注意,在过渡期间,旧元素和新元素都存在并且是布局的一部分,除非通过样式另有指定。这会导致布局变化,因为默认情况下会占用两倍的空间。您可以将其他样式应用于例如绝对定位消失的元素,使它们不占用空间。

    【讨论】:

      猜你喜欢
      • 2021-09-13
      • 2020-12-31
      • 1970-01-01
      • 2021-09-09
      • 2021-11-09
      • 2021-01-31
      • 1970-01-01
      • 1970-01-01
      • 2017-06-24
      相关资源
      最近更新 更多