Html 是否可以通过 CSS 将输入字段设为只读?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16811045/
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-08-29 08:51:40  来源:igfitidea点击:

Is it possible to make input fields read-only through CSS?

javascripthtmlcssprinting

提问by mark

I know that input elements are made read-only by applying the readonlyboolean attribute, and being an attribute it is not affected by CSS.

我知道通过应用readonly布尔属性将输入元素设为只读,并且作为一个不受 CSS 影响的属性。

On the other hand, my scenario seems to be a very good fit for CSS, so I was hoping there is some kind of a CSS trick to let me do it. I have a printable versionhyperlink on my form. Clicking it displays a ... printable version of the document. It is mostly CSS stuff, my print.css looks like this:

另一方面,我的场景似乎非常适合 CSS,所以我希望有某种 CSS 技巧可以让我做到这一点。我的表单上有一个可打印版本的超链接。单击它会显示文档的 ... 可打印版本。它主要是 CSS 的东西,我的 print.css 看起来像这样:

html.print {
    width: 8.57in;
}

.print body {
    font: 9pt/1.5 Arial, sans-serif;
    margin: 0 1in;
    overflow: auto;
}

.print #header, .print #footer {
    display: none;
}

.print .content {
    background-color: white;
    overflow: auto;
}

.print .fieldset > div.legend:first-child {
    background: white;
}

.print ::-webkit-input-placeholder {
    /* WebKit browsers */
    color: transparent;
}

.print :-moz-placeholder {
    /* Mozilla Firefox 4 to 18 */
    color: transparent;
}

.print ::-moz-placeholder {
    /* Mozilla Firefox 19+ */
    color: transparent;
}

.print :-ms-input-placeholder {
    /* Internet Explorer 10+ */
    color: transparent;
}

.print .check-mark {
    display: inline;
}

.print input[type=checkbox] {
    display: none;
}

.print .boolean-false {
    display: none;
}

There are also a few javascript pieces, such as:

还有一些javascript部分,例如:

  • Adding the printclass to the html element
  • Displaying tables without scroll bars
  • A few other minor things, like hiding any popup overlays.
  • print类添加到 html 元素
  • 显示没有滚动条的表格
  • 其他一些小事情,比如隐藏任何弹出式覆盖。

My current problem is input fields. They should be read-only, however, I have no idea how to do it with minimum changes to the code. CSS could be a perfect solution.

我目前的问题是输入字段。它们应该是只读的,但是,我不知道如何以最少的代码更改来做到这一点。CSS 可能是一个完美的解决方案。

Any ideas?

有任何想法吗?

采纳答案by James Donnelly

With CSS only? This is sort of possible on text inputs by using user-select:none:

仅使用 CSS?这在文本输入上是可能的,使用user-select:none

.print {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;          
}

JSFiddle example.

JSFiddle 示例

It's well worth noting that this will not work in browsers which do not support CSS3 or support the user-selectproperty. The readonlyproperty should be ideally given to the input markup you wish to be made readonly, but this does work as a hacky CSS alternative.

值得注意的是,这在不支持 CSS3 或不支持user-select属性的浏览器中不起作用readonly理想情况下,该属性应该提供给您希望只读的输入标记,但这确实可以作为一种 hacky CSS 替代方案。

With JavaScript:

使用 JavaScript:

document.getElementById("myReadonlyInput").setAttribute("readonly", "true");

Edit:The CSS method no longer works in Chrome (29). The -webkit-user-selectproperty now appears to be ignored on input elements.

编辑:CSS 方法不再适用于 Chrome (29)。该-webkit-user-select属性现在似乎在输入元素上被忽略。

回答by Faust

It is not (with current browsers) possible to make an input field read-only through CSS alone.

仅通过 CSS 无法(使用当前浏览器)将输入字段设为只读。

Though, as you have already mentioned, you can apply the attribute readonly='readonly'.

不过,正如您已经提到的,您可以应用属性readonly='readonly'

If your main criteria is to not alter the markup in the source, there are ways to get this in, unobtrusively, with javascript.

如果您的主要标准是不更改源代码中的标记,则可以使用 javascript 不显眼地实现这一点。

With jQuery, this is easy:

使用 jQuery,这很容易:

 $('input').attr('readonly', true);

Or even with plain Javascript:

或者甚至使用普通的 Javascript:

document.getElementById('someId').setAttribute('readonly', 'readonly');

回答by Cétia

Not really what you need, but it can help and answser the question here depending of what you want to achieve.

不是你真正需要的,但它可以帮助和回答这里的问题,这取决于你想要实现的目标。

You can prevent all pointer events to be sent to the input by using the CSS property : pointer-events:noneIt will kind of add a layer on top of the element that will prevent you to click in it ... You can also add a cursor:textto the parent element to give back the text cursor style to the input ...

您可以使用 CSS 属性阻止将所有指针事件发送到输入:pointer-events:none它会在元素顶部添加一个图层,以防止您单击它...您还可以cursor:text向父元素添加一个将文本光标样式返回给输入...

Usefull, for example, when you can't modify the JS/HTML of a module.. and you can just customize it by css.

很有用,例如,当您无法修改模块的 JS/HTML 时..而您可以通过 css 对其进行自定义。

JSFIDDLE

JSFIDDLE

回答by Jee Mok

The read-onlyattribute in HTML is used to create a text input non-editable. But in case of CSS, the pointer-eventsproperty is used to stop the pointer events.

read-onlyHTML 中的属性用于创建不可编辑的文本输入。但是在 CSS 的情况下,该pointer-events属性用于停止指针事件。

Syntax:

句法:

pointer-events: none;

Example:This example shows two input text, in which one is non-editable.

示例:此示例显示了两个输入文本,其中一个是不可编辑的。

<!DOCTYPE html> 
<html> 
    <head> 
        <title> 
            Disable Text Input field 
        </title> 

        <style> 
        .inputClass { 
            pointer-events: none; 
        } 
        </style> 
    </head> 

    <body style = "text-align:center;">
        Non-editable:<input class="inputClass" name="input" value="NonEditable"> 

        <br><br> 

        Editable:<input name="input" value="Editable"> 
    </body> 
</html>                  

Edit static

编辑静态

回答by Roy Sonasish

This is not possible with css, but I have used one css trick in one of my website, please check if this works for you.

这对于 css 是不可能的,但是我在我的一个网站中使用了一种 css 技巧,请检查这是否适合您。

The trick is: wrap the input box with a div and make it relative, place a transparent image inside the div and make it absolute over the input text box, so that no one can edit it.

诀窍是:用一个 div 包裹输入框并使其相对,在 div 内放置一个透明图像并使其绝对在输入文本框上,这样任何人都无法对其进行编辑。

css

css

.txtBox{
    width:250px;
    height:25px;
    position:relative;
}
.txtBox input{
    width:250px;
    height:25px;
}
.txtBox img{
    position:absolute;
    top:0;
    left:0
}

html

html

<div class="txtBox">
<input name="" type="text" value="Text Box" />
<img src="http://dev.w3.org/2007/mobileok-ref/test/data/ROOT/GraphicsForSpacingTest/1/largeTransparent.gif" width="250" height="25" alt="" />
</div>

jsFiddle File

jsFiddle 文件

回答by David Jashi

No behaviors can be set by CSS. The only way to disable something in CSS is to make it invisible by either setting display:noneor simply putting div with transparent img all over it and changing their z-orders to disable user focusing on it with mouse. Even though, user will still be able to focus with tab from another field.

CSS 不能设置任何行为。在 CSS 中禁用某些内容的唯一方法是通过设置display:none或简单地将透明 img 放在 div 上并更改其 z-orders 以禁用用户使用鼠标关注它来使其不可见。尽管如此,用户仍然可以使用来自另一个字段的选项卡进行聚焦。

回答by Ian Danforth

Why not hide the input element and replace it with a label element with the same content?

为什么不隐藏 input 元素并替换为具有相同内容的 label 元素?

I puzzled over how the React TODOMVC app accomplished this same thing and this is the strategy they came up with.

我对 React TODOMVC 应用程序如何完成同样的事情感到困惑,这就是他们提出的策略。

To see it in action, check out the app below, and watch the CSS properties of the TODO items when you double click them and then click away.

要查看它的实际效果,请查看下面的应用程序,并在双击 TODO 项然后单击离开时查看它们的 CSS 属性。

http://todomvc.com/examples/react-backbone/#/

http://todomvc.com/examples/react-backbone/#/

When you render the page you can have either an editable input, or a non-editable label with display:none; depending on your media query.

当你渲染页面时,你可以有一个可编辑的输入,或者一个带有 display:none; 的不可编辑的标签。取决于您的媒体查询。

回答by Alpesh Panchal

CSS based input text readonly change color of selection:

基于 CSS 的输入文本只读更改选择的颜色:

CSS:

CSS:

/**default page CSS:**/
::selection { background: #d1d0c3; color: #393729; }
*::-moz-selection { background: #d1d0c3; color: #393729; }

/**for readonly input**/
input[readonly='readonly']:focus { border-color: #ced4da; box-shadow: none; }
input[readonly='readonly']::selection { background: none; color: #000; }
input[readonly='readonly']::-moz-selection { background: none; color: #000; }

HTML:

HTML:

<input type="text" value="12345" id="readCaptch" readonly="readonly" class="form-control" />

live Example:https://codepen.io/alpesh88ww/pen/mdyZBmV

现场示例:https : //codepen.io/alpesh88ww/pen/mdyZBmV

also you can see why i was done!! (php captcha):https://codepen.io/alpesh88ww/pen/PoYeZVQ

你也可以看到我为什么完成了!!(php验证码):https : //codepen.io/alpesh88ww/pen/PoYeZVQ

回答by sAnS

You don't set the behavior of controls via CSS, only their styling.You can use jqueryor simple javascriptto change the property of the fields.

您不能通过 设置控件的行为CSS,而只能通过它们的样式设置。您可以使用jquery或 simplejavascript来更改字段的属性。

回答by RachithaS

Hope this will help.

希望这会有所帮助。

    input[readonly="readonly"]
{
    background-color:blue;
}

reference:

参考:

http://jsfiddle.net/uzyH5/1/

http://jsfiddle.net/uzyH5/1/