css - Blazor:如何在运行时设置 CSS 类的背景图像?
问题描述
我知道我可以在设计时做到这一点:
.page-background-class {
background-image:url(../images/image-name.png)
}
但是如何在运行时设置背景图像?我想显示登录用户的图像。我想使用 URL,但也可以嵌入。
TIA,
解决方案
你在正确的路线上。忘记 Javascript,你在 Blazor 中。我看不到你在哪里使用这张图片,所以我不能谈论细节,但你需要考虑组件 - 我的用户显示的东西是什么。如何使其成为组件 - Blazor UI 中的所有内容都是组件!
为了使演示更容易,我将在组件上设置背景颜色而不是图像。
创建一个 Razor 组件 -MyBackground.razor
<div style=" background-color:@this.Color" @attributes="Attributes">
@ChildContent
</div>
@code {
[Parameter] public string Color { get; set; }
[Parameter] public RenderFragment ChildContent { get; set; }
[Parameter(CaptureUnmatchedValues = true)] public IDictionary<string, object> AdditionalAttributes { get; set; }
private IDictionary<string, object> Attributes
{
get
{
var attr = "style";
if (this.AdditionalAttributes != null)
if (this.AdditionalAttributes.ContainsKey(attr)) this.AdditionalAttributes.Remove(attr);
return AdditionalAttributes;
}
}
}
然后您可以使用它 - 我已将其添加到Index.razor
标准模板中
@page "/"
@using TestBlazorServer.Components
<MyBackground Color="@this.color" class="p-5" style=" background-color:black">
<h1 class="border-primary">Hello, world!</h1>
Welcome to your new app.
<SurveyPrompt Title="How is Blazor working for you?" />
</MyBackground>
@code{
private string color { get; set; } = "#bbf";
}
我添加了一些额外的属性,因此您可以看到组件如何处理这些属性。 class
被通过,而style
被移除 - 背景是蓝色而不是黑色,具有很好的宽填充边距。
您的组件的基本代码如下所示:
<div style="background-image:@this.ImageUrl" @attributes="Attributes">
@ChildContent
// Or Html code to build out my UserDisplay Component
</div>
@code {
[Parameter] public string ImageUrl { get; set; }
[Parameter] public RenderFragment ChildContent { get; set; }
[Parameter(CaptureUnmatchedValues = true)] public IDictionary<string, object> AdditionalAttributes { get; set; }
private IDictionary<string, object> Attributes
{
get
{
var attr = "style";
if (this.AdditionalAttributes != null)
if (this.AdditionalAttributes.ContainsKey(attr)) this.AdditionalAttributes.Remove(attr);
return AdditionalAttributes;
}
}
}
将任何特定的组件 CSS 放入组件 CSS 文件中。 组件 CSS 上的 MS Docs
推荐阅读
- html - 引导导航栏在暴民视图中不起作用当我单击按钮时下拉菜单不显示
- node.js - Ionic 和 React Native 应用程序是否在 Android 和 iOS 设备的节点服务器上运行?
- azure - Azure 数据湖文件中的逻辑视图
- typesafe - HOCON : 如何限制基数包括
- reactjs - 如何在反应引导行事件中使用删除按钮执行删除功能?
- java - 如何在多对一关系中选择被 n 个父实体引用的子实体?
- c++ - 对序列进行分区以最小化差异
- javascript - 如何从电子表格中获取值以显示在我的网络应用程序上?
- sql - TSQL:在每列中为所有行查找奇数和偶数
- python - 正则表达式在数字序列中查找数字、连字符和逗号