【问题标题】:Autofocus on EditorFor自动对焦于 EditorFor
【发布时间】:2015-08-23 16:42:52
【问题描述】:

我想在我的应用程序中自动对焦于编辑器,但我似乎无法做到。我已经成功地在文本框上使用了自动对焦,但我想使用编辑器来保持我的应用程序的通用性。

对此问题的任何解决方案将不胜感激,谢谢。

我的尝试:

@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" }, autofocus = "" })

【问题讨论】:

  • @DavidG 是的,我也试过了。

标签: html asp.net-mvc razor


【解决方案1】:

这是因为您使用的是 EditorFor 而不是 TextBoxFor 之类的特定内容。

@Html.TextBoxFor(model => model.Name, new { htmlAttributes = new { 
                    @class = "form-control" }, autofocus="autofocus"})

或者你可以使用 jQuery 来做到这一点:

<div class="editor-field focus">
    @Html.EditorFor(model => model.Description)
    @Html.ValidationMessageFor(model => model.Description)
</div> 
$(function() {
    $('.focus :input').focus();
});

更新
如您所知,TextBoxFor 总是创建一个带有类型输入的文本框,但EditorFor 有点聪明,它根据属性的数据类型呈现标记。

【讨论】:

  • 你是说为了使用自动对焦,输入数据类型不能有歧义吗?
  • @Jon 如果您查看 EditorFor 的重载,则没有任何接受 htmlAttributes 的重载。您实际使用的重载正在使用 AdditionalViewData。
  • 谢谢,我对 asp.net 还很陌生,还没有学到很多 jQuery,但是你的 jQuery 解决方案对我来说非常有效。
【解决方案2】:

使用 .Net Framework 4.5 和 MVC 5,这对我有用:

@Html.EditorFor(model => model.Description, new {
    htmlAttributes = new {
        @class = "form-control",
        autofocus = true
    }
})

【讨论】:

    【解决方案3】:

    你把自动对焦属性放错了位置。

    @Html.EditorFor(model => model.Description, 
         new { htmlAttributes = new { @class = "form-control" }, autofocus = "" })
    

    试试这个:

    @Html.EditorFor(model => model.Description, 
         new { htmlAttributes = new { @class = "form-control", autofocus = "" } })
    

    【讨论】:

      【解决方案4】:

      我一直在关注这个帖子,我可能偶然发现了一个关于 EditorFor 自动对焦的问题的答案 - 这都是 Asp.Net 4.5 和 MVC 5,并不重要。

      1. 在 Scripts 文件夹中,我有一个 jQuery 脚本文件:

        $(函数(){ $('.someclassname').focus(); });

      我将脚本名称添加到 BundleConfig 并在视图中呈现。

      1. 在视图中,我将类名添加到 EditorFor &lt;div class="col-md-10" someclassname"&gt;
      2. 然后我将type="text" autofocus="autofocus" 添加到EditorFor 的@class。所以,new{@class="form-control", type="text", autofocus="autofocus"
      3. 差不多就是这样,当 DOM 加载时,.someclassname 字段获得光标焦点... PS。事实上,如果你只做 (3) 它也可以......

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-23
        • 2021-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-12
        • 1970-01-01
        • 2019-11-15
        相关资源
        最近更新 更多