简体   繁体   English

如何在 Blazor 中使用 C# 动态更改 HTML 背景

[英]How to dynamically change HTML background using C# in Blazor

Javascript can easily manipulate DOM elements as well as css to dynamically change the appearance of the application. Javascript 可以轻松操作 DOM 元素以及 css 以动态更改应用程序的外观。 I would like to dynamically change the background image of the DOM element dynamically using c# in a blazor application.我想在 blazor 应用程序中使用 c# 动态更改 DOM 元素的背景图像。

 document.getElementById('the_body').style.backgroundImage = "something.gif" $('body').css('backgroundImage', 'url(something.gif)');
 body { background: #000000 url(images/back_all.gif) repeat-x top; font: 12px Tahoma, Arial, Helvetica, sans-serif; color: #666666; }

How do I obtain the same result in C# Blazor application?如何在 C# Blazor 应用程序中获得相同的结果?

To change the background (or anything for that matter) of an element that you have in a component, you can declare private fields, or use some similar pattern:要更改组件中元素的背景(或任何相关内容),您可以声明私有字段,或使用一些类似的模式:

<div style="background-image: url(@backgroundUrl)">
</div>
<button type="button" @onclick="ChangeBackground">Change above div's background</button>

@code {
    string backgroundUrl = "default.jpg";

    private void ChangeBackground()
    {
        backgroundUrl = "some-other-image.jpg";
        StateHasChanged();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM