我想创建一个接收图像名称和路径的 svelte 组件。我想让组件使用 CSS 将图像设置为“背景图像”。
我尝试了以下似乎不起作用的方法...
App.svelte 中调用的组件:
<Image image_url='./images/image1.jpg' />
Run Code Online (Sandbox Code Playgroud)
图像.Svelte
<script>
export let image_url;
</script>
<style>
.image{
position:relative;
opacity: 0.70;
background-position:bottom;
background-size: cover;
background-repeat: no-repeat;
background-attachment: fixed;
background-image: url({image_url});
min-height: 100%;
}
</style>
<div class="image">
<p>some text</p>
</div>
Run Code Online (Sandbox Code Playgroud)
当我检查组件时,background_image 的 css 是:
background-image: url({image_url});
Run Code Online (Sandbox Code Playgroud)
是否可以在 CSS 中转换变量?
Ric*_*ris 28
不会。组件样式在组件的所有实例之间共享,因为它们被静态提取到 .css 文件中,或者因为它们被注入到<style>所有组件引用的单个元素中。如果可以将变量直接放入组件的 中<style>,则意味着 Svelte 需要为每个实例创建封装样式,这将不利于性能并且会消耗更多内存。
有两种方法可以解决这个问题。第一种是对可以更改每个实例的任何内容使用内联样式:
<script>
export let image_url;
</script>
<style>
.image{
position:relative;
opacity: 0.70;
background-position:bottom;
background-size: cover;
background-repeat: no-repeat;
background-attachment: fixed;
/* background-image: url({image_url}); */
min-height: 100%;
}
</style>
<!-- <div class="image"> -->
<div class="image" style="background-image: url({image_url});">
<p>some text</p>
</div>
Run Code Online (Sandbox Code Playgroud)
第二种,特别是当你需要在多个地方使用值时,是使用 CSS 变量:
<script>
export let image_url;
</script>
<style>
.image{
position:relative;
opacity: 0.70;
background-position:bottom;
background-size: cover;
background-repeat: no-repeat;
background-attachment: fixed;
/* background-image: url({image_url}); */
background-image: var(--image);
min-height: 100%;
}
</style>
<!-- <div class="image"> -->
<div class="image" style="--image: url({image_url});">
<p>some text</p>
</div>
Run Code Online (Sandbox Code Playgroud)
coy*_*508 17
您现在可以直接将 css 变量作为 props 传递:https://svelte.dev/docs#template-syntax-component-directives---style-props
<Image --background-image='url(./images/image1.jpg)' />
Run Code Online (Sandbox Code Playgroud)
在Image.svelte
background-image: var(--background-image, url(./images/default.jpg));
Run Code Online (Sandbox Code Playgroud)