我想使用 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 nowthe 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 但仍然没有。
源代码
此处为 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}
此外,您不需要 bind:this
并且可以使用事件对象:
function doStuff(e) {
e.target.scrollIntoView();
}
关于javascript - 在 :animationend can't access bind:this svelte (undefined) 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73919242/