如何将变量绑定到由{@html svg}包含的任意SVG元素?

huangapple go评论64阅读模式
英文:

How do I bind variables to arbitrary elements of an svg included by {@html svg}?

问题

我正在使用{@html svg}将一个动态生成的SVG文件包含到一个组件中。我需要进行一些操作。SVG中包含了嵌入式脚本,但它们没有触发,而且我认为它们可能无法正常工作(它们使用getElementById)。

所以,如果我能将变量绑定到包含的SVG中的任意元素,那么我可以放置脚本来执行所需的操作。有没有办法让我将变量绑定到由{@html svg}包含的预生成的动态SVG中的任意元素?我知道我不能像使用getElementById那样做事情,但我也不能使用bind:this。谢谢!

英文:

I'm including a dynamically generated SVG file into a component using {@html svg}. I need to do some magic. The SVG has embedded scripts, but they're not triggering, and I don't think they'd work anyway (they use getElementById).

So if I can just bind variables to arbitrary elements in the included SVG, then I could put scripts in place to do what needs to be done. Is there a way for me to bind variables to arbitrary elements in a pregenerated, dynamic SVG being included by {@html svg}? I know I can't do things like getElementById, but I also can't use bind:this. Thanks!

答案1

得分: 2

Querying the DOM is usually not necessary since there are better alternative ways with Svelte. But in case the elements are created via {@html}, I think there's no other way to get a reference to them. They are accessible inside the onMount callback when the component has been mounted to the DOM.

英文:

Querying the DOM is usually not necessary since there are better alternative ways with Svelte. But in case the elements are created via {@hmtl} I think there's no other way to get a reference to them. They are accessible inside the onMount callback, when the component has been mounted to the DOM.

<script>
	import {onMount} from 'svelte'

	onMount(() => {
		const rect = document.getElementById('rect')
		console.log(rect)
	})

	const svg = '<svg viewBox="0 0 220 100" xmlns="http://www.w3.org/2000/svg"><rect id="rect" width="100" height="100" /></svg>'
</script>

{@html svg}

huangapple
  • 本文由 发表于 2023年5月15日 10:55:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76250617.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定