【发布时间】:2016-12-23 13:06:43
【问题描述】:
我写了一个自定义助手:
public static MvcHtmlString TextBoxForWithTooltip<Tmodel, TProperty>(this HtmlHelper<Tmodel> htmlHelper, Expression<Func<Tmodel, TProperty>> expression, object htmlAttributes = null, string tooltip = "")
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
IDictionary<string, object> attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (!string.IsNullOrEmpty(metaData.Description))
{
attributes.Add("title", metaData.Description);
}
if (!string.IsNullOrWhiteSpace(tooltip))
{
attributes.Add("data-tooltip", tooltip);
}
if (attributes.ContainsKey("style"))
{
var val = attributes["style"];
attributes["style"] = val + ";border-radius: 6px;";
}
else
{
attributes.Add("style", "border-radius: 6px;");
}
return htmlHelper.TextBoxFor(expression, attributes);
}
还有我从 [这里][1] 获得的 CSS。当您将数据工具提示分配给按钮或“a”或“li”元素时,这非常有用。但不是输入或 TextBoxFor。我在页面源中看到了 data-tooltip 属性,但它显然不会触发 CSS 来显示工具提示。有谁知道为什么?
其实我做的是这样的:
public static MvcHtmlString TextBoxForWithTooltip<Tmodel, TProperty>(this HtmlHelper<Tmodel> htmlHelper, Expression<Func<Tmodel, TProperty>> expression, object htmlAttributes = null, string tooltip = "")
{
IDictionary<string, object> attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (attributes.ContainsKey("style"))
{
var val = attributes["style"];
attributes["style"] = val + ";border-radius: 6px;";
}
else
{
attributes.Add("style", "border-radius: 6px;");
}
return MvcHtmlString.Create("<div data-tooltip='" + tooltip + "'>" + htmlHelper.TextBoxFor(expression, attributes) + "</div>");
}
我在 DIV 中嵌入了 html 以获取工具提示。
【问题讨论】:
-
这是因为 CSS 使用了
:before和:after伪元素,这些伪元素不适用于input和textarea等替换元素(img也是如此,select更多信息请参见developer.mozilla.org/en-US/docs/Web/CSS/Replaced_element)