我要求使用红色星号标记。我需要带有标签的类,这些标签是我的应用程序中必填字段。应用程序中有很多表单。我使用下面的代码尝试使用jquery。
$(".required").each(function(){
$(this).prepend("<span class='red'>*</span>");
});
任何人都可以帮我用css来应用它。帮助将不胜感激。
答案 0 :(得分:7)
为什么不只是CSS?
label.required::before {
content: '*';
margin-right: 4px;
color: red;
}
&#13;
<form>
<label for="input1" class="required">Label One</label>
<input type="text" id="input1" />
</form>
&#13;
答案 1 :(得分:3)
尽管@ isherwood的答案符合您的要求,但这是一种有趣的替代方法:
使用required
上的input
属性而不是类。通过label
反转float
位置,然后在符合所需属性集的输入的标签上使用::after
伪元素。
<强> 演示 强>:
div.form { width: 240px; }
div.form input {
float: right;
}
input[required] + label::after {
content: '*';
display: inline-block;
color: red;
}
br {
clear: both; }
}
<div class="form">
<input id="i1" />
<label for="i1">Label: </label>
<br>
<input id="i1" required />
<label for="i1">Label: </label>
<br>
<input id="i1" />
<label for="i1">Label: </label>
<br>
<input id="i1" required />
<label for="i1">Label: </label>
</div>
答案 2 :(得分:1)
我会使用类似下面的JQuery。 (虽然它确实取决于确切的HTML)。
$(".required").append(
$("<span>").addClass("red").text("*");
);
然后对于CSS而言,只需
.required.red { color: rgb(255,0,0); }
注意:CSS中的颜色属性可以通过多种不同方式指定。 rgb方法只是我的默认首选项。
答案 3 :(得分:0)
如果你正在使用bootstrap .. 它很简单..
<label> Label Name <span class="symbol required"></span></label>
答案 4 :(得分:0)
如果您想使用 静态方法 ,则可以在以下实现:
public static IHtmlContent RequiredLabelFor<TModel, TValue>(this IHtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, object htmlAttributes = null)
{
if (htmlHelper == null) throw new ArgumentNullException(nameof(htmlHelper));
if (expression == null) throw new ArgumentNullException(nameof(expression));
var viewData = htmlHelper.ViewData;
var modelMetadata = viewData?.ModelMetadata;
var metadataProvider = htmlHelper.MetadataProvider;
var modelExpressionProvider = (ModelExpressionProvider)htmlHelper.ViewContext.HttpContext.RequestServices.GetService(typeof(IModelExpressionProvider));
var modelExplorer = modelExpressionProvider.CreateModelExpression(viewData, expression);
if (modelExplorer == null) throw new InvalidOperationException($"Failed to get model explorer for {modelExplorer}");
var metaData = modelExplorer.Metadata;
var propertyName = metaData.PropertyName ?? viewData?.ModelMetadata?.Name;
if(propertyName==null) throw new NullReferenceException("Unable to retrieve property");
var modelExpression = modelExpressionProvider.CreateModelExpression(viewData,expression);
var labelText = modelExpression?.Model ?? metaData.DisplayName;
IDictionary<string, object> attributes = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
if (htmlAttributes == null)
{
attributes.Add("class", "control-label");
}
else
{
attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
var classAttributes = attributes.Where(x => x.Key == "class").Select(x => x.Value).ToList();
if (!classAttributes.Contains("control-label"))
{
attributes["class"] += " control-label";
}
}
var highlightClass = "required required-label-color";
TagBuilder tagBuilder = new TagBuilder("label");
tagBuilder.Attributes.Add("for", !string.IsNullOrEmpty(Name) ? Name : propertyName);
tagBuilder.InnerHtml.AppendHtml($"{labelText} (<span class='{highlightClass}'>*</span>)");
tagBuilder.MergeAttributes(attributes);
var content = new HtmlContentBuilder().AppendHtml(tagBuilder);
return content;
}
如果要使用非静态 c方法,则可以执行以下操作:
<label-required for="@Model.Title"></label-required>
[HtmlTargetElement("label-required")]
public class RequiredLabelTagHelper : TagHelper
{
// Will be used as highlight-class in html
[HtmlAttributeName("highlight-class")]
public string HighlightClass { get; set; } = "required required-label-color";
[HtmlAttributeName("class")]
public string MainClass { get; set; } = "control-label";
[HtmlAttributeName("name")]
public string Name { get; set; }
public override int Order => -1000;
[HtmlAttributeNotBound]
[ViewContext]
public ViewContext ViewContext { get; set; }
protected IHtmlGenerator Generator { get; }
/// <summary>
/// An expression to be evaluated against the current model.
/// </summary>
[HtmlAttributeName("for")]
public ModelExpression For { get; set; }
public RequiredLabelTagHelper(IHtmlGenerator generator)
{
Generator = generator;
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (output == null)
{
throw new ArgumentNullException(nameof(output));
}
var modelExplorer = For?.ModelExplorer;
var metaData = For?.Metadata;
var propertyName = For?.Name ?? metaData?.PropertyName;
var labelText = metaData?.DisplayName ?? propertyName; //For?.Model?.ToString();
var htmlAttributes = new { @class = MainClass };
TagBuilder tagBuilder;
if (For != null)
{
tagBuilder = Generator.GenerateLabel(
ViewContext,
modelExplorer,
propertyName,
labelText: labelText,
htmlAttributes: htmlAttributes);
}
else
{
tagBuilder = new TagBuilder("label");
if (!string.IsNullOrEmpty(Name))
{
tagBuilder.Attributes.Add("for", Name);
}
}
// Do not update the content if another tag helper targeting this element has already done so.
if (!output.IsContentModified)
{
output.MergeAttributes(tagBuilder);
output.TagName = tagBuilder.TagName;
output.TagMode = TagMode.StartTagAndEndTag;
var requiredMarkTagBuilder = new TagBuilder("span");
requiredMarkTagBuilder.AddCssClass(HighlightClass);
requiredMarkTagBuilder.InnerHtml.Append(" *");
// We check for whitespace to detect scenarios such as: <label for="Name"></label>
var childContent = await output.GetChildContentAsync().ConfigureAwait(true);
if (childContent.IsEmptyOrWhiteSpace)
{
// Provide default label text (if any) since there was nothing useful in the Razor source.
if (tagBuilder.HasInnerHtml)
{
tagBuilder.InnerHtml.AppendHtml(requiredMarkTagBuilder);
output.Content.SetHtmlContent(tagBuilder.InnerHtml);
}
}
else
{
using (var writer = new StringWriter())
{
childContent.WriteTo(writer, HtmlEncoder.Default);
requiredMarkTagBuilder.WriteTo(writer, HtmlEncoder.Default);
output.Content.SetHtmlContent(writer.ToString());
}
}
}
}
}