首页 文章

输入字段的一个占位符中的2种颜色

提问于
浏览
8

我需要在占位符中创建具有2种颜色的输入 .

这是解决方案,在Chrome中运行良好 .

http://jsfiddle.net/vmuJm/

html

<input placeholder="Name" class="required" />

css

.required::-webkit-input-placeholder:after {
    content:'*';
    color: red;
}
.required:-moz-placeholder:after {
    /* Firefox 18- */
    content:'*';
    color: red;
}
.required::-moz-placeholder:after {
    /* Firefox 19+ */
    content:'*';
    color: red;
}
.required:-ms-input-placeholder:after {
    content:'*';
    color: red;
}

但是我目前的FF 29.0.1没有显示内容:之后,所以这个解决方案不起作用 . 有没有其他方法可以在一个占位符中使用css和html获得2种颜色?

Chrome:

https://lh5.googleusercontent.com/-NN7pPNg49D8/U5DUKMAIJhI/AAAAAAAAzAg/LqltLDSNgD4/s0/2014-06-05_22-33-08.png

FF:

enter image description here

3 回答

  • 0

    这是一个不使用Javascript的跨浏览器解决方案:

    Live demo

    内联元素 input 不支持 :before:after . 为了使事情变得更加困难,所有浏览器都不完全支持占位符选择器及其伪类,正如您所发现的那样 .

    因此,解决方法是将 label 相对放置在输入框的顶部,并使用 for 属性指向输入文本框 . 这样,当用户点击标签(假占位符)时,焦点就会进入输入框 .

    用属性 required="required" 替换 class="required" . 这使您有机会使用:invalid:valid选择器 .

    <form>
        <input type="text" id="name" name="name" required="required" />
        <label for="name">Name</label>
        
    <input type="email" id="email" name="email" placeholder="Email" />
    <input type="submit" /> </form> input { width: 160px; } input[type=submit] { width: auto; } input[required] + label { color: #999; font-family: Arial; font-size: .8em; position: relative; left: -166px; /* the negative of the input width */ } input[required] + label:after { content:'*'; color: red; } /* show the placeholder when input has no content (no content = invalid) */ input[required]:invalid + label { display: inline-block; } /* hide the placeholder when input has some text typed in */ input[required]:valid + label{ display: none; }

    由于电子邮件不是必需的,请将原始占位符保留在那里,而只是为了这个名称 .

    我还将您的电子邮件从 type="text" 更改为 type="email" ,以便在移动设备上获得更好的用户体验 .

  • 0

    问同样的问题here

    基本上答案是否定的 . 取决于浏览器 .

    :before:after 不能用于某些元素,例如 <input> . 它取决于浏览器,因为它似乎可以做到这一点 .

    也许它可以用JavaScript解决?我不知道

  • 13

    受Jose的解决方案的启发,不使用"required"属性,live demo也可以做你想要的 .

    关键点是css有 :not 选择器,参考Mozilla website

相关问题