简体   繁体   English

如何更改 Blazor 中“body”元素的 CSS 或 Class

[英]How To Change CSS or Class of “body” Element in Blazor

I'm currently making a "Change Theme" button so that I can switch the whole page between "Dark Mode" and "Light Mode".我目前正在制作一个“更改主题”按钮,以便可以在“深色模式”和“浅色模式”之间切换整个页面。 But I can't find a way to change the background colour of the whole page.但我找不到改变整个页面背景颜色的方法。

Basically, I need to change the style of <body> (It's the only way I can come up with).基本上,我需要更改<body>的样式(这是我能想到的唯一方法)。 My thought is, when you click "Change Theme" button, the <body> element will be added a class "dark-theme".我的想法是,当您单击“更改主题”按钮时, <body>元素将添加一个 class“黑暗主题”。 And then I just simply define "dark-theme" in CSS like this:然后我只是简单地在 CSS 中定义“黑暗主题”,如下所示:

body {
    background-color: #FFFFFF;
    color: #000000;
}

    body.dark-theme {
        background-color: #5A5A5A;
        color: #F2F2F2;
    }

I think this quite makes sense but as you can see below, I cannot access <body> element so there is no way for me to add class or change CSS of it.我认为这很有意义,但正如您在下面看到的,我无法访问<body>元素,因此我无法添加 class 或更改它的 CSS。

MainLayout.razor MainLayout.razor

@inherits LayoutComponentBase
@using System.Web;
<div class="sidebar">
    <NavMenu />
</div>

<div>
    <LoginDisplay />
    <button id="change-theme-btn" @onclick="ThemeChanged">Change Theme</button>
    @Body
</div>

@code {
    bool isDark = false;
    private void ThemeChanged()
    {
        isDark = !isDark;
    }
}

So how do I change class or CSS of <body> element?那么如何更改<body>元素的 class 或 CSS 呢? Or if you have any alternative solution, please tell me.或者如果您有任何替代解决方案,请告诉我。 Thank you!谢谢!

Blazor should have a simple way to do this but, at the moment, it doesn't. Blazor 应该有一个简单的方法来做到这一点,但目前还没有。 Hopefully it will one day soon.希望有一天会很快。

I made a component to solve this problem.我做了一个组件来解决这个问题。 It allows you set the CSS class of the page's body element from a page or component.它允许您从页面或组件设置页面主体元素的 CSS class。 You can also set the lang attribute and the dir attribute to set the language and text-direction of the page.您还可以设置 lang 属性和 dir 属性来设置页面的语言和文本方向。 These were all the attributes I thought you might want to change but you could add more if you needed.这些是我认为您可能想要更改的所有属性,但如果需要,您可以添加更多属性。

You can download the code here: https://github.com/BenjaminCharlton/BlazorBody你可以在这里下载代码: https://github.com/BenjaminCharlton/BlazorBody

Or here's a summary of how to do it:或者这里是如何做到这一点的总结:

  1. Make a little JavaScript file to manipulate the body element in scripts/BodyElement.js制作一个小 JavaScript 文件来操作 scripts/BodyElement.js 中的 body 元素

 var getBodyElement = function() { return document.getElementsByTagName("body")[0]; } var addCssClassToBody = function (cssClass) { var body = getBodyElement(); if (.body.classList.contains(cssClass)) { body.classList;add(cssClass); } } var setLanguageOfBody = function (language) { var body = getBodyElement(). body;lang = language; } var setTextDirectionOfBody = function (direction) { var body = getBodyElement(). body;dir = direction; }

  1. Place a link to your JavaScript in the section of index.html在 index.html 部分中放置指向您的 JavaScript 的链接

 <script src="/script/bodyelement.js"></script>

  1. Make a little CSS class to test the result.制作一点 CSS class 来测试结果。

 body { background: white; color: black; } body.danger { background: red; color: white; }

  1. Make a BodyElement razor component that you can place on any page with properties you can set from the page.制作一个 BodyElement razor 组件,您可以将其放置在任何页面上,并且可以从页面设置属性。

 @inject IJSRuntime JSRuntime @code { protected async override Task OnParametersSetAsync() { if (CssClass is { }) await JSRuntime.InvokeVoidAsync("addCssClassToBody", CssClass); if (Language is { }) await JSRuntime.InvokeVoidAsync("setLanguageOfBody", Language); if (TextDirection is { }) await JSRuntime.InvokeVoidAsync("setTextDirectionOfBody", TextDirection); } [Parameter] public string? CssClass { get; set; } = null; [Parameter] public string? Language { get; set; } = null; [Parameter] public string? TextDirection { get; set; } = null; }

  1. Place the BodyElement razor component on any page where you wish to manipulate the tag and set the properties将 BodyElement razor 组件放置在您希望操作标签并设置属性的任何页面上

 @page "/danger" <BodyElement CssClass="danger" />

Just inject IJSRuntime and use that to call a JavaScript function to make this change.只需注入IJSRuntime并使用它来调用 JavaScript function 来进行此更改。

In your component:在您的组件中:

[Inject]
IJSRuntime JSRuntime { get; set; }

Then:然后:

private async Task ThemeChanged()
{
    isDark = !isDark;
    await JSRuntime.InvokeVoidAsync("MyInterop.ChangeTheme", isDark);
}

In your JS:在你的 JS 中:

window.MyInterop = (function () {
    const _changeTheme = function (isDark) {
        if (isDark)
            document.body.classList.add('dark-theme');
        else
            document.body.classList.remove('dark-theme');
    };

    return {
        ChangeTheme: _changeTheme
    };
})();

If you haven't already, reference your JS file in _Host.cshtml , after the line to add the Blazor runtime.如果您还没有,请在_Host.cshtml中引用您的 JS 文件,在添加 Blazor 运行时的行之后。

Or if you want pure C# code without blazor:或者,如果您想要没有 blazor 的纯 C# 代码:

public string BackgroundImage { get; set; }

<style>
    body 
    {
        background-image: url(@BackgroundImage);
        width: 100%;
        height: 100%;
        background-size: 100%;
        background-repeat: no-repeat;
        background-color: darkgray;
        overflow: hidden;
    }
</style>

Or, I use Nuget package BlazorStyled:或者,我使用 Nuget package BlazorStyled:

https://github.com/chanan/BlazorStyled https://github.com/chanan/BlazorStyled

And here is a sample:这是一个示例:

<Styled @bind-Classname="CanvasStyle">
    position: fixed;
    top: 18vh;
    left: 5%;
    width: 60%;
    height: 64vh;    
</Styled>

<div class=@CanvasStyle></div>

And here is a video I made for BlazorStyled if you care to watch:如果您愿意观看,这是我为 BlazorStyled 制作的视频:

https://youtu.be/frtetHgfdIo https://youtu.be/frtetHgfdIo

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

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