问题
I have a typical div element in a cshtml page in the form:
<div id="loginErrors" class="alert alert-danger hide-errors">@(ErrorMessage)</div>
pre Blazor, I'd typically use jQuery to add or remove the hide-errors
class from the div. However, Blazor is trying to remove the need for JavaScript and I'm trying to use as little JSInterop as possible. Is there a way in Blazor to do this?
so in Blazor I could do:
@if (!string.IsNullOrEmpty(ErrorMessage))
{
<div id="loginErrors" class="alert alert-danger">@(ErrorMessage)</div>
}
else
{
<div id="loginErrors" class="alert alert-danger hide-errors">@(ErrorMessage)</div>
}
or using JSinterop :
the Call for removing:
await JSRuntime.Current.InvokeAsync<object>("blazorExtensions.RemoveClass", "loginErrors", "hide-errors");
where the function would typically be :
RemoveClass: function (id, classname) {
var tt = '#' + id;
$(tt).removeClass(classname);
}
with similar for adding a class. Both of the above work, but as mentioned. I'm trying to avoid the JSInterop route and I don't like the div element being declared twice even though only one will get into the DOM.
回答1:
Just like you would in regular Razor:
@if (price>30)
{
<p>The price is too high.</p>
}
EDIT For updated question, I guess you want this:
<div class="@((string.IsNullOrEmpty(ErrorMessage)? "hide-errors" : ""))">
回答2:
This is very easy as you can change any part of an html element dynamically in Blazor without using Javascript. After so many years I admit, it took me a little while to get out of the old Javascript mindset, but once you do, Blazor rocks!
In your html somewhere use a variable for the class name (or other attributes) of any html element you want to make dynamic style (or other) modifications to.
<img class="@myImageClass" src="@myImg" />
In @functions declare any variables you created...
@functions {
string myImageClass { get; set; }
string myImg { get; set; } // Swap out the image as well if you want.
if you want to set items to something initially use OnInit()
protected override void OnInit()
{
myImageClass = "myImageVisible";
myImg = "https://www.somesite.com/ImageToStartWith.png"
}
Somewhere in a function change to the desired class to something you pre-defined in the style section.
private async Task DoSomething()
{
myImageClass = "myImageHidden";
myImg = "https://www.somesite.com/NewImageToSwapIn.png"
//Not sure what the point of swapping an image on a hidden element is
//but you get the idea. You can change anything you want anytime.
}
Don't forget to define some styles you want to use beforehand.
<style>
.myImageVisible {
display: block;
}
.myImageHidden{
display: none;
}
</style>
Enjoy. :)
来源:https://stackoverflow.com/questions/54087863/how-to-change-classes-of-a-div-element-using-blazor