【发布时间】:2026-01-16 22:30:01
【问题描述】:
使用 Svelte,我想要完成的是能够使用我拥有的 post 对象的 css 属性设置我的 html 样式。
我想,没问题,只需将样式标签添加到我的svelte:head 和{post.css}。它将我的post.css 数据直接放入样式标签,中提琴,问题解决了。但是,不,问题没有解决。当我在浏览器中查看元素时,我看到了
<style>{post.css}</style>
而不是
<style>
p{
color: purple;
font-weight: 900;
}
</style>
我创建了一个解决方法,我在<style> 标记之后设置了innerText onMount,但我不喜欢它,并且希望以更简洁的方式来做。
我想要什么……
<script>
export let post = {
html: `<p>This is purple</p>`,
css : `
p{
color: purple;
font-weight: 900;
}
`
}
</script>
<svelte:head>
<style>{post.css}</style>
</svelte:head>
{@html post.html}
我必须做些什么才能让它发挥作用……
<script>
import { onMount } from "svelte";
export let post = {
html: `<p>This is purple</p>`,
css : `
p{
color: purple;
font-weight: 900;
}
`
}
onMount(() => {
let styler = document.getElementById("styler");
styler.innerText = post.css
});
</script>
<svelte:head>
<style id="styler"></style>
</svelte:head>
{@html post.html}
如果您有任何其他替代方法可以使用css 属性来设置post 对象的html 属性的样式,或者知道如何让Svelte 识别{post.css} 在<style> 标记中,请让我知道。
【问题讨论】: