[英]How to set dynamic background image URL with linear gradient using custom CSS class in Angular
I would like to be able to set a background-image
using a dynamically loaded image (from my server) along with a linear gradient overlay using a custom CSS class.我希望能够使用动态加载的图像(来自我的服务器)以及使用自定义 CSS 类的线性渐变叠加来设置background-image
。 On page load, the CSS should look like this:在页面加载时,CSS 应如下所示:
.container {
background-image: linear-gradient(transparent -30%,#121212), url(https://...)
}
However, the color: #121212
needs to be set using a custom css variable called --ion-color-dark
and the url is stored in an http response object: this.response.imageURL
但是,颜色: #121212
需要使用名为--ion-color-dark
的自定义 css 变量进行设置,并且 url 存储在 http 响应对象中: this.response.imageURL
So I would need something like this:所以我需要这样的东西:
.container {
background-image: linear-gradient(transparent -30%,var(--ion-color-dark)), url(`${this.response.imageURL}`)
}
My solution so far:到目前为止我的解决方案:
I've figured out how to get the image url to load by doing the following in my HTML:我已经弄清楚如何通过在我的 HTML 中执行以下操作来加载图像 url:
<div class="container" [ngStyle]="{'background-image': getBackgroundImageURL()}"></div>
Which calls getBackgroundImageURL()
in my component:在我的组件中调用getBackgroundImageURL()
:
getBackgroundImageURL() {
return `linear-gradient(transparent -30%,#121212, url(${this.response.imageURL})`;
}
Which is great, but I cannot figure out how to load the CSS variable to replace the hard coded #121212
using this method.这很好,但我不知道如何使用这种方法加载 CSS 变量来替换硬编码的#121212
。 It appears I can do either one or the other, but not both.看来我可以做一个或另一个,但不能同时做。
Any suggestions?有什么建议? Thanks!谢谢!
You can do this by defining the variable in this way-您可以通过以这种方式定义变量来做到这一点 -
getBackgroundImageURL() { return linear-gradient(transparent -30%,var(--my-variable-name)), url(${this.response.imageURL})
; getBackgroundImageURL() { return linear-gradient(transparent -30%,var(--my-variable-name)), url(${this.response.imageURL})
; } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.