简体   繁体   English

在 CSS 或 JavaScript 中不更改背景颜色的情况下将输入字段设为只读

[英]Make input field readonly without changing background colour in CSS or JavaScript

I would like to make a HTML input field readonly but without getting the grey background that appears when I just add the attribute readonly (it should look the same as a normal field just not allow editing).我想将 HTML 输入字段设为只读,但不会在我添加属性 readonly 时出现灰色背景(它应该看起来与普通字段相同,只是不允许编辑)。

Is there a way I can realise this in CSS and/or JS, ideally with a class ?有没有办法可以在 CSS 和/或 JS 中实现这一点,最好是使用类?

Example field:示例字段:

<input type="text" style="width:96%" class="myClass" />

I think you mistook disabled and readonly我想你误认为禁用和只读

<input type="text" value="readonly" readonly>
<input type="text" value="disabled" disabled>

have a look to this fiddle : http://jsfiddle.net/36UwE/看看这个小提琴: http : //jsfiddle.net/36UwE/

As you can see, only the disabled input is grey (tested on Windows with latest Chrome & IE)如您所见,只有禁用的输入是灰色的(在 Windows 上使用最新的 Chrome 和 IE 进行了测试)

However, this may differ, according the browser, operating system and so on.但是,这可能会有所不同,具体取决于浏览器、操作系统等。 You can use custom the display with css:您可以使用 css 自定义显示:

input[readonly] {
  background-color: white;
}

Yes, you can use the :disabled pseudo class, eg是的,您可以使用 :disabled 伪类,例如

input.myClass:disabled {
    /* style declaration here */
}

While you can apply any styling using :disabled, :readonly or .myClass CSS selectors, be aware that different browsers/platforms will render the standard, readonly & disabled input fields differently, so trying to override color, borders and background based on the defaults for your platform (eg Windows) might break the styling on other platforms (eg Mac).虽然您可以使用 :disabled、:readonly 或 .myClass CSS 选择器应用任何样式,但请注意,不同的浏览器/平台将以不同的方式呈现标准、只读和禁用的输入字段,因此尝试根据默认值覆盖颜色、边框和背景对于您的平台(例如 Windows)可能会破坏其他平台(例如 Mac)上的样式。

It's usually not a good idea to override the default styling cues that users expect, but if you must do this then you should ensure that readonly/disabled input fields are visually discernible from standard ones, and use custom styling that is not platform-specific.覆盖用户期望的默认样式提示通常不是一个好主意,但如果您必须这样做,那么您应该确保只读/禁用的输入字段与标准输入字段在视觉上可区分,并使用非平台特定的自定义样式。

<input type="text" class="form-control" value="MyText" readonly />

<style>
    input.form-control:read-only {
        background-color: #fff;
    }
</style>

or或者

<input type="text" class="form-control" value="MyText" style="background-color: #fff;" readonly />

More info here .更多信息在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM