【问题标题】:getClientBoundingRect for conditionally rendered element with animation in SveltegetClientBoundingRect 用于 Svelte 中带有动画的条件渲染元素
【发布时间】:2020-12-05 00:31:22
【问题描述】:

给定带有下拉菜单的条件渲染 div。为了计算它的位置(向上或向下打开),我需要获取它的高度和宽度。

当然,在过渡完成之前元素没有得到正确的尺寸。

所以问题是 - 如何以编程方式关闭转换?或者如何在不显示元素的情况下获得元素的未来位置?

{#if isOpened}
    <div
        bind:this={thisMenu}
        use:clickOutside
        on:click_outside={closeHandler}
        class="dropdown absolute left-100p text-gray-600 z-10 w-full animated
        rounded-lg"
        style={finalStyle}
        {isInit ?  null : transition:slide }>
        <slot name="list" />
    </div>
{/if}

【问题讨论】:

    标签: svelte-3 svelte-component svelte-transition


    【解决方案1】:

    slide-transition 使用 getComputedStyle,所以也许这就是你需要的。以下内容是从 svelte 存储库 (src/runtime/transition/index.ts) 中的幻灯片函数复制而来的。滑动功能将这些值从零设置为初始值并返回。

    const style = getComputedStyle(node);
    const opacity = +style.opacity;
    const height = parseFloat(style.height);
    const padding_top = parseFloat(style.paddingTop);
    const padding_bottom = parseFloat(style.paddingBottom);
    const margin_top = parseFloat(style.marginTop);
    const margin_bottom = parseFloat(style.marginBottom);
    const border_top_width = parseFloat(style.borderTopWidth);
    const border_bottom_width = parseFloat(style.borderBottomWidth);
    

    编辑: @bobfanger 在 cmets 中解释了如何制作自定义 mySlide-function,并且在该函数中,有可用的初始大小值。这是一个工作示例:

    <script>
      import {slide} from "svelte/transition"
      let show=false 
      let d
      function mySlide(el) { 
        let s=window.getComputedStyle(d)
        console.log("mySlide",s.height)
        return slide(el, {duration:2000})
      }
    </script>
    <h1 on:click={()=>show=show?false:true}>Click me</h1>
    {#if show}
    <div bind:this={d} transition:mySlide
     style="background-color:yellow;padding:10px;border:10px solid;">
      <p>test</p>
    </div>
    {/if}
    

    这比使用onMountvisibility hacks 简单得多。

    【讨论】:

    • 我认为为了计算将被转换的 div - 我们必须在没有动画的情况下将其闪烁。然后如果用户打开菜单 - 我们已经知道打开它的方向。
    • 基本上我试图防止在外部或视口打开菜单时出现这种情况
    • 我找不到在 thr 组件安装后和动画开始之前运行的生命周期方法(这是滑动函数读取元素初始尺寸的时刻)。因此,我现在找到的唯一方法是在创建时设置元素 visibility:hidden;position:absolute 并读取尺寸。然后将样式值设置回正常值并让动画运行。
    • 这里是 REPL,在 onMount-function 中检索元素高度(console.log),然后元素准备好动画:svelte.dev/repl/57d9f664dac84921910abed394cabb5d?version=3.24.1
    • @BobFanger 感谢您提供新信息。我注意到transition: 仅在显示el 时运行mySlide-function(动画仍然可以双向运行),但in:MySlideout:mySlide 分别运行该函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 2015-12-04
    • 2021-10-06
    • 2018-07-04
    • 1970-01-01
    相关资源
    最近更新 更多