How to style readonly attribute with CSS?

后端 未结 9 1646
忘了有多久
忘了有多久 2020-12-12 21:45

I\'m currently using readonly=\"readonly\" to disable fields. I\'m now trying to style the attribute using CSS. I\'ve tried using

input[readonly] {
/*styling         


        
相关标签:
9条回答
  • 2020-12-12 21:49
    input[readonly]
    {
        background-color:blue;
    }
    

    https://curtistimson.co.uk/post/css/style-readonly-attribute-css/

    0 讨论(0)
  • 2020-12-12 21:56

    Use the following to work in all browsers:

     var readOnlyAttr = $('.textBoxClass').attr('readonly');
        if (typeof readOnlyAttr !== 'undefined' && readOnlyAttr !== false) {
            $('.textBoxClass').addClass('locked');
        }
    
    0 讨论(0)
  • 2020-12-12 21:57
    input[readonly], input:read-only {
        /* styling info here */
    }
    

    Shoud cover all the cases for a readonly input field...

    0 讨论(0)
  • 2020-12-12 21:58

    Note that textarea[readonly="readonly"] works if you set readonly="readonly" in HTML but it does NOT work if you set the readOnly-attribute to true or "readonly" via JavaScript.

    For the CSS selector to work if you set readOnly with JavaScript you have to use the selector textarea[readonly].

    Same behavior in Firefox 14 and Chrome 20.

    To be on the safe side, i use both selectors.

    textarea[readonly="readonly"], textarea[readonly] {
    ...
    }
    
    0 讨论(0)
  • 2020-12-12 21:58

    Loads of answers here, but haven't seen the one I use:

    input[type="text"]:read-only { color: blue; }
    

    Note the dash in the pseudo selector. If the input is readonly="false" it'll catch that too since this selector catches the presence of readonly regardless of the value. Technically false is invalid according to specs, but the internet is not a perfect world. If you need to cover that case, you can do this:

    input[type="text"]:read-only:not([read-only="false"]) { color: blue; }
    

    textarea works the same way:

    textarea:read-only:not([read-only="false"]) { color: blue; }
    

    Keep in mind that html now supports not only type="text", but a slew of other textual types such a number, tel, email, date, time, url, etc. Each would need to be added to the selector.

    0 讨论(0)
  • 2020-12-12 22:04

    If you select the input by the id and then add the input[readonly="readonly"] tag in the css, something like:

     #inputID input[readonly="readonly"] {
         background-color: #000000;
     }
    

    That will not work. You have to select a parent class or id an then the input. Something like:

     .parentClass, #parentID input[readonly="readonly"] {
         background-color: #000000;
     }
    

    My 2 cents while waiting for new tickets at work :D

    0 讨论(0)
提交回复
热议问题