javascript - 在 :animationend can't access bind:this svelte (undefined) 上

标签 javascript css dom-events svelte

我想使用 querySelector() 但我发现 Svelte 有另一种方法可以做到这一点。

通过使用bind:this


问题是有时它会起作用,但大多数时候它永远不会起作用

通过输出undefined

这是一个简单的例子:

<script>
  let thisDiv;

  console.log(thisDiv) // ❌ "undefined" ✅ "<div>"
</script>

<div bind:this={thisDiv}>hello world</div>

真正的错误

但真正的问题在这里

because I don't need to console.log for now

the things I wrote before are only for making you understand the bug
so I can start putting more information.

因为我有一个使用该变量的函数
并在“on:animationend”事件开始时调用该函数。

像这样:

<div
  bind:this={thisDiv}
  on:animationend={doStuff()}
></div>

问题是 animationend 仍然 console.log thisDiv undefined

可能是速度的问题?

是的,好的...

但 CSS 中的动画只有 50 毫秒长。还尝试了 0.5s

并且 CSS 不会阻止 javascript,因此当 CSS 执行他的动画时 js 将继续工作(据我所知)

和 0.5s 我认为做一个简单的 bind:this (querySelector)

这怎么可能?半秒后得到一个正常的 querySelector 但仍然没有。

enter image description here


源代码

此处为 REPL 在线 svelte 源代码示例:

https://svelte.dev/repl/b49d019ce7f8426b80295158b091520f?version=3.50.1

make sure to uncomment the line 9 in child.svelte

...或者直接看这个

App.svelte

<script>
    import Child from "./Child.svelte"
    
    function generateExample() {
        let output = [];
        
        for(let i=0; i<=100; i++) {
            output = [
                ...output, `text ${i}`
            ]
        }
        
        return output;
    }
    
  let array = generateExample()
</script>

{#each array as item, index}
   <Child {index}>
      {item}
   </Child>
{/each}

child . slim

<script>
  export let index;
  const DELAY = 50;
  
  let thisDiv;

    // UNCOMMENT THE NEXT LINE
  function doStuff() {
         // thisDiv.scrollIntoView(); 
  }
</script>

<div
  style="--delay:{index * DELAY}ms;"
  bind:this={thisDiv}
  on:animationend={doStuff()}
  >
  <slot></slot>
</div>

<style>
  div {
    animation: show var(--delay);
  }

  @keyframes show {
    from {
      translate: 100vw;
    }
    to {
      translate: 0;
    }
  }
</style>

最佳答案

实际上,您的代码有问题,您调用了处理程序而不是引用它:

on:animationend={doStuff()}

应该是:

on:animationend={doStuff}

REPL

此外,您不需要 bind:this 并且可以使用事件对象:

function doStuff(e) {
    e.target.scrollIntoView();
}

REPL

关于javascript - 在 :animationend can't access bind:this svelte (undefined) 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73919242/

相关文章:

javascript - 动态表格单元格 ID 和名称在 IE 浏览器的 Jquery 中不可更新

javascript - Chart JS — 条件水平行背景色

未调整图像的 HTML 链接

javascript - HTML5/CSS/JS 网络应用程序和 native 应用程序的通用代码库

javascript - Angular : ignore messages emitted by self

javascript - 在 setTimeout 回调函数中保留 event.clientX 值

javascript - 实时过滤json

javascript - 从同一类 div jquery 中查找不同的文本框值

javascript - 将鼠标悬停在另一个对象上时更改显示 CSS

javascript - 为什么这段 JavaScript 代码(作为 HTML 属性嵌入)不起作用?