简体   繁体   English

如何在 Svelte 中使用 JS 变量中的 CSS?

[英]How to use CSS from JS variable in Svelte?

Please check a Svelte component below:请检查下面的 Svelte 组件:

<script>
    import CodeViewer from '$lib/CodeViewer.svelte';

    const code = `       .ezy-rotate-180 {
            transition: 0.5s, color 0.1s;
            -webkit-transition: 0.5s, color 0.1s;
            -moz-transition: 0.5s, color 0.1s;
        }
        .ezy-rotate-180:hover {
            transform: rotate(180deg);
            -webkit-transform: rotate(180deg);
            -moz-transform: rotate(180deg);
        }`;
    const language = 'css';
</script>

<div class="flex flex-row flex-wrap w-full">
    <div class="w-1/2">
                    <!-- 1. added CSS class here
                             ↓   -->
            <div class="ezy-rotate-180 px-10 py-2 bg-slate-50 text-black w-28 text-center rounded-md">Rotate 180</div>
    </div>

    <CodeViewer {code} {language} />
</div>

<style>
    {code} /* <== 2. I tried this, but not working */
</style>

In this component, I have CSS in a JS variable.在这个组件中,我在 JS 变量中有 CSS。 I want apply the same CSS to a div and show it to through CodeViewer component.我想将相同的 CSS 应用于div并通过CodeViewer组件显示它。 CodeViewer is working as expected. CodeViewer正在按预期工作。

But how I can apply that CSS (from JS variable) to a div ?但是我如何将 CSS (来自 JS 变量)应用到div

You cannot use interpolations in the <style> element.您不能在<style>元素中使用插值。 You can apply style properties via the style attribute on elements but not CSS rules.您可以通过元素上的style属性应用样式属性,但不能应用 CSS 规则。

For something like this you could programmatically create a style element in onMount which then can be updated when the code changes, something like:对于这样的事情,您可以通过编程方式在onMount中创建一个样式元素,然后可以在代码更改时对其进行更新,例如:

let style;

onMount(() => {
    style = document.createElement('style');
    document.head.append(style);
    
    return () => style.remove(); // Cleanup on destroy
});

$: if (style) style.textContent = code;

REPL REPL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM