javascript 设置只读属性以保持输入可编辑

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11011172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:48:50  来源:igfitidea点击:

set readonly attribute to keep the input editable

javascriptjqueryhtml

提问by DamianS1987

Is it possible to set "readonly" attribute of an input to keep it editable?

是否可以设置输入的“只读”属性以使其可编辑?

I'm doing a crossword and I can change my function to search for/select a tag using different attribute but I'm still wondering if it is possible.

我正在做一个填字游戏,我可以更改我的功能以使用不同的属性搜索/选择标签,但我仍然想知道是否有可能。

Thanks for help in advance!

提前感谢您的帮助!

回答by Quentin

If the JavaScript readOnlyproperty is set to true(a boolean, not a string), then the control will not be editable.

如果 JavaScriptreadOnly属性设置为true(布尔值,而不是字符串),则控件将不可编辑。

If the JavaScript readOnlyproperty is set to false(a boolean, not a string), then the control will be editable.

如果 JavaScriptreadOnly属性设置为false(布尔值,而不是字符串),则控件将是可编辑的。

If the HTML readonlyattribute is present, then the readOnlyproperty will default to true.

如果存在 HTMLreadonly属性,则该readOnly属性将默认为true

If the HTML readonlyattribute is not present, then the readOnlyproperty will default to false.

如果 HTMLreadonly属性不存在,则该readOnly属性将默认为false

JavaScript can modify the valueproperty of a control no matter what state the readOnlyproperty has.

value无论属性处于何种状态,JavaScript 都可以修改该控件的readOnly属性。

There is no way for a control to be edited through the normal browser UI if it is set to readOnly(JavaScript consoles and DOM inspectors are not the normal UI).

如果设置为readOnly(JavaScript 控制台和 DOM 检查器不是普通 UI),则无法通过普通浏览器 UI 编辑控件。

回答by KooiInc

The attribute readonlyrenders the input control noneditable for a user. Using javascript you can still change its value. Setting the readonlyattribute in javascript to falsehas no effect for the user, the input still will be readonly. Removing the attribute will render the input editable for the user again.

该属性readonly使用户无法编辑输入控件。使用 javascript 你仍然可以改变它的值。将readonlyjavascript 中的属性设置false为对用户没有影响,输入仍然是readonly. 删除该属性将再次为用户呈现可编辑的输入。

You could also use the disabledattribute, with two differences: the field is displayed grayed out, and you canset the disabledattribute directly.

您也可以使用该disabled属性,但有两点不同:字段显示为灰色,您可以disabled直接设置该属性。

It's all tested/demonstrated in this jsfiddle[note: updated]

这一切都在这个 jsfiddle 中进行了测试/演示[注意:更新]

回答by Jamie Pate

I suggest using the html5 supported data- prefix data-readonly="true" https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes

我建议使用 html5 支持的数据前缀 data-readonly="true" https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes