How to set placeholder value using CSS?

后端 未结 9 1290
天涯浪人
天涯浪人 2020-12-16 09:00

I want to set the placeholder value of an input box using only css and not JavaScript or jQuery. How can I do this?

9条回答
  •  执念已碎
    2020-12-16 09:26

    Another way this can be accomplished, and have not really seen any others give it as an option, is to instead use an anchor as a container around your input and label, and handle the removal of the label via some color trickory, the #hashtag, and the css a:visited. (jsfiddle at the bottom)

    Your HTML would look like this:

    
        
        
    
    

    And your CSS, something like this:

    html, body {margin:0px}
    a#Trickory {color: #CCC;} /* Actual Label Color */
    a#Trickory:visited {color: #FFF;} /* Fake "Turn Off" Label */
    
    a#Trickory:visited input {border-color: rgb(238, 238, 238);} /* Make Sure We Dont Mess With The Border Of Our Input */
    
    a#Trickory input:focus + label {display: none;} /* "Turn Off" Label On Focus */
    
    a#Trickory input {
        width:95%;
        z-index:3;
        position:relative;
        background-color:transparent;
    }
    a#Trickory label {
        position:absolute;
        pointer-events: none;
        display:block;
        top:3px;
        left:4px;
        z-index:1;
    }
    

    You can see this working over at jsfiddle, note that this solution only allows the user to select the field once, before it removes the label for good. Maybe not the solution you want, but definitely an available solution out there that I have not seen others mention. If you want to experiment multiple times, just change your #hashtag to a new 'non-visited' tag.

    http://jsfiddle.net/childerskc/M6R7K/

提交回复
热议问题