首页 > 解决方案 > Blazor:如何在运行时设置 CSS 类的背景图像?

问题描述

我知道我可以在设计时做到这一点:

.page-background-class {
background-image:url(../images/image-name.png)

}

但是如何在运行时设置背景图像?我想显示登录用户的图像。我想使用 URL,但也可以嵌入。

TIA,

标签: cssblazor

解决方案


你在正确的路线上。忘记 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


推荐阅读