我可以使用传递给组件的变量来设置svelte样式的css属性值吗 [英] Can I set svelte style css attribute values using variables passed in to a component
本文介绍了我可以使用传递给组件的变量来设置svelte样式的css属性值吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个svelte组件,它接收图像的名称和路径。我想让组件使用CSS将图像设置为"背景图像"。
我尝试了以下方法,但似乎不起作用...
App.svelte中调用的组件:
<Image image_url='./images/image1.jpg' />
Image.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>
当我检查组件时,BACKGROUND_IMAGE的CSS为:
background-image: url({image_url});
可以在css中转换变量吗?
推荐答案
否。组件样式在组件的所有实例之间共享,因为它们被静态提取到.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>
第二个是使用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>
这篇关于我可以使用传递给组件的变量来设置svelte样式的css属性值吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文