Microsoft Edge显示HTML5日期选择器,用于输入由
定义的输入的值<input type="date">
有没有办法显示一个清除按钮或'x'装饰,以便之后删除该值,就像Google Chrome浏览器一样?
答案 0 :(得分:8)
这里最好的选择可能是隐藏Chrome提供的自定义清除标记,并为所有浏览器提供自己的选择:
input::-webkit-clear-button {
display: none;
}
然后,您将提供自己的清除按钮:
<input type="date" required />
<button>Clear</button>
最后,只要点击按钮,就可以清除输入的一小段逻辑:
(function () {
"use strict";
var elmnt = document.querySelector( "input" );
var clear = document.querySelector( "button" );
clear.addEventListener( "click", function ( event ) {
elmnt.value = "";
});
}());
我希望这会有所帮助。
答案 1 :(得分:0)
我从 Where did the clear button go on date type input elements in Chrome? 中的简单示例开始。
<input id=el type=datetime-local value="2025-07-01T12:44">
<button onclick="javascript:el.value=''">X</button>
并将其转换为我的 C# ASP.NET Web 应用程序中的扩展方法。
public static System.Web.IHtmlString editorWithClearFor<TModel, TValue>(
this System.Web.Mvc.HtmlHelper<TModel> helper,
System.Linq.Expressions.Expression<Func<TModel, TValue>> expression,
object additionalViewData )
{
//------------------------------
// Determine the input element ID.
// The ID might be the property name.
ModelMetadata metadata = ModelMetadata.FromLambdaExpression( expression, helper.ViewData );
string inputElemId = metadata.PropertyName;
//------------------------------
// The ID might be specified in the HTML attributes within the view data.
Type t = additionalViewData.GetType();
PropertyInfo pi = t.GetProperty( "htmlAttributes" );
IDictionary<string, object> attribs = pi.GetValue( additionalViewData, null ) as IDictionary<string, object>;
if ( attribs.ContainsKey( "id" ) )
{
inputElemId = attribs["id"].ToString();
}
//------------------------------
// For the input and the button to be side by side,
// must I must wrap each of them in a div? That seems to be the only thing that works.
//------------------------------
// Input.
IHtmlString input = helper.EditorFor( expression, additionalViewData );
//------------------------------
// Wrap the input in a div.
TagBuilder div1 = new TagBuilder( "div" );
div1.MergeAttribute( "style", "display: inline-block;" );
div1.InnerHtml = input.ToString();
//------------------------------
// Clear button.
TagBuilder btn = new TagBuilder( "button" );
btn.MergeAttribute( "title", "Clear" );
btn.MergeAttribute( "style", "border: none; background-color: transparent;" );
btn.MergeAttribute( "onclick", String.Format( "javascript:{0}.value=''", inputElemId ) );
btn.InnerHtml = "X";
//------------------------------
// Wrap the button in a div.
TagBuilder div2 = new TagBuilder( "div" );
div2.MergeAttribute( "style", "display: inline-block;" );
div2.InnerHtml = btn.ToString();
//------------------------------
// Concatenate.
Debug.WriteLine( div1.ToString() + div2.ToString() );
return MvcHtmlString.Create( div1.ToString() + div2.ToString() );
}
cshtml 标记中的示例用法:
@Html.editorWithClearFor( m => m.DueDate, new { htmlAttributes = new { "class", "form-control" } } )