Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change css directly(without variable) in Blazor?

I am using the server-side of Blazor.

I want to change the CSS of the body.

In Jquery I can write the code like this easily:

$("body").css("overflow-y","hidden");

However, with this tutorial(Blazor Change Validation default css class names) said, it seems I can only change the CSS by changing the class name.

It is so complex while crossing the component, especially the body is at the top of all the components.

I wonder whether there is a way can changes CSS directly in Blazor. Thank you.

like image 691
Melon NG Avatar asked Oct 08 '19 05:10

Melon NG


People also ask

How do I add custom CSS to Blazor?

Add a CSS File to a ProjectCopy a CSS file with your styles to the wwwroot/css folder. Add the CSS file link to the head section of the layout file: Pages/_Layout. cshtml in Blazor Server apps.

What is dynamic CSS?

This is a collection of methods which give you the ability to query the stylesheets collection in a document, add and remove rules, and dynamically create new sheets.

How do you use CSS in razor page?

All you have to do is to place a style sheet in the Pages folder alongside the page that it is intended to affect. You just need to follow a specific naming convention, which is the Razor page file name with . css on the end. The bundled file itself is placed in the wwwroot folder when the application is published.


1 Answers

There are several ways of getting out of the "blazor way" of doing things and accomplishing css modification of an element.

Simplest: Just like you can use the class attribute, use the style attribute

<element style=@myStyle></element>

@code {
  string myStyle;

  void MyMethod() {
     myStyle="overflow-y: hidden;"
  }
}

Advanced: Use JS interop

a. In the main view (index.html or Pages/_Host.cshtml depending on project type), create a js endpoint for your component

<script>
   window.applyStyleForElement = function(styleOp) {
       document.getElementById(styleOp.id).style[styleOp.attrib] = styleOp.value;
   }
</script>

b. In razor file:

@Inject IJRRuntime JSRuntime
<element id=@myId></element>

@code {
  string myId = Guid.NewGuid().ToString("n");

  async Task MyMethod() {
     await JSRuntime.InvokeAsync("applyStyleForElement", 
      new { id = myId,  attrib = "overflowY", value = "hidden" });
  }
}

Finally, applying to your special case with body element ("advanced" method above).

a. In the main view (index.html or Pages/_Host.cshtml depending on project type), create a js endpoint

<script>
   window.applyStyleForBody = function(style) {
       document.body.style[style.attrib] = style.value;
   }
</script>

b. In razor file:

@Inject IJRRuntime JSRuntime
(...)

@code {

  async Task MyMethod() {
     await JSRuntime.InvokeAsync("applyStyleForBody", 
       new { attrib = "overflowY", value = "hidden" });
  }
}
like image 107
Tewr Avatar answered Oct 21 '22 07:10

Tewr