【问题标题】:Can not set readonly on input field in IE无法在 IE 中的输入字段上设置只读
【发布时间】:2015-04-05 08:08:47
【问题描述】:

我有一个简单的输入框:

<input id="myInput" class="someClass"></input>

还有一些 JQuery 代码:

$(e.currentTarget).prop('readonly', true);

e.currentTarget 是 [object HTMLInputElement] 的 IE11 名称。

我只是想将此输入字段设置为只读。在 chrome 中该代码有效,但在 IE 中无效。 我已经试过了:

.prop('readonly','readonly');
.prop('readonly', '');
.attr('readonly', true);

但它们都不能在 IE11 中工作(在 chrome 中每个人都工作)

【问题讨论】:

  • 你试过 .attr('readOnly', true); ??
  • @jrenk:如果prop 不起作用,attr 将不起作用。
  • 它工作正常。输入在 IE 中变为只读。 (我使用$('input') 作为选择器)。
  • @MrUpsidown:区别似乎在于相关字段是否具有焦点。
  • @T.J.Crowder 我没听懂。你的意思是IE这个领域仍然可以聚焦?

标签: javascript jquery google-chrome internet-explorer


【解决方案1】:

好吧,这很奇怪:如果你将字段设为只读而它有焦点,IE11 似乎有点疯狂,这是它的一种方式go bonkers 是让您在光标在那里时继续修改字段 - 使用 some 击键,但不使用其他击键。这是一个例子:Fiddle

$("#myInput").one("click", function(e) {
    $(e.currentTarget).prop('readonly', true);
    display("e.currentTarget.readOnly: " + e.currentTarget.readOnly);
});
$("#myInput").on("keydown", function(e) {
    display("e.currentTarget.readOnly: " + e.currentTarget.readOnly);
});
function display(msg) {
    $("<p>").html(String(msg)).appendTo(document.body);
}

添加这一行之前设置readOnly修复它(fiddle):

$(e.currentTarget).blur();

旁注:您不需要 jQuery 来设置 readOnly 属性,只需:

e.currentTarget.readOnly = true; // Note the capital O

【讨论】:

  • 谢谢。但知道它会在 chrome 中引发严重的角度错误;)但这是另一个问题的主题。
【解决方案2】:

“只读”输入元素在 IE 8、9、10 或 11 中无法始终如一地工作。

在这种情况下,我们可以在输入元素中使用onkeydown="javascript: return false;"。

【讨论】:

    【解决方案3】:

    我在带有 ID 的 jquery 端使用了 Focusin() 函数。当我点击文本框时,我们删除 readony 属性如下:

    HTML:

    <input type="text" id="txtCustomerSearch" readonly class="customer-search" 
       placeholder="Search customer:" maxlength="100" autocomplete="off">
    

    jquery:

    $("#txtCustomerSearch").focusin(function () {
        $(this).removeAttr('readonly');
    

    });

    注意:它可以在IE11和其他浏览器中运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-08
      • 2021-11-23
      • 2021-08-14
      • 1970-01-01
      相关资源
      最近更新 更多