【问题标题】:How to get asterisk in placeholder with css如何使用 css 在占位符中获取星号
【发布时间】:2019-09-11 23:49:05
【问题描述】:

我想为输入的占位符添加一个星号。像这样的东西:

我搜索了互联网,但找不到可行的解决方案。

HTML:

<input type="text" name="your-name" placeholder="Naam">

我目前的做法:

目前我正在尝试将其添加到 after 伪元素中,但没有出现。

input[type=text]::-webkit-input-placeholder:after {
   content: '*';
   color: red; vertical-align: top; font-size: 10px;
}

input[type=text]:-moz-placeholder:after { /* Firefox 18- */
   content: '*'; 
   color: red; vertical-align: top; font-size: 10px;
}

input[type=text]::-moz-placeholder:after {  /* Firefox 19+ */
   content: '*';
   color: red; vertical-align: top; font-size: 10px;
}

input[type=text]:-ms-input-placeholder:after {  
   content: '*';
   color: red; vertical-align: top; font-size: 10px;
} 

我不想直接在占位符中添加符号。但会喜欢它以任何其他方式让我以不同的方式设置符号样式。(比如我想要符号为蓝色,但其余文本为灰色)。

所以,如果有人可以帮我在占位符上添加一个星号。

JSFIDDLE

【问题讨论】:

  • @BhojendraNepal 但这不会让我设计它。假设我想为星号添加不同的颜色。
  • 星号 符号应保留在标签中,以将字段显示为必填字段,而不是在占位符上。
  • 是的@Shashank。但是我的客户也希望我将其添加到占位符中。所以,如果可以的话,我正在寻找一种方法。
  • @BhojendraNepal。你能指导我如何做到这一点吗?
  • 我已经为你解答了。

标签: html css


【解决方案1】:

为什么不直接在占位符属性中使用 *?

.asterisk::-webkit-input-placeholder {
    color:    #f00;
}
.asterisk:-moz-placeholder {
   color:    #f00;
   opacity:  1;
}
.asterisk::-moz-placeholder {
   color:    #f00;
   opacity:  1;
}
.asterisk:-ms-input-placeholder {
   color:    #f00;
}
&lt;input type="text" name="your_name" placeholder="*" class="asterisk" /&gt;

尾注:replaced html elements中不能使用伪元素


根据您的评论,您还可以使用 required 属性,然后像这样设置它们的样式:

<input type="text" name="your_name" placeholder="*" required />
[required]::-webkit-input-placeholder {
    color:    #f00;
}

根据您的下一个评论要求,您需要将需要星号的输入包装在如下范围内:

.input-group{
  position: relative;
}
.input-group::after{
  content: '*';
  position: absolute;
  top: 3px;
  left: 46px;
  color: #f00
}
<span class="input-group">
  <input type="text" name="your_name" placeholder="Naam" />
</span>

【讨论】:

  • 但这会将颜色添加到整个占位符。我想要的是:只有占位符中的星号符号为灰色,占位符中的其他文本为红色。
  • 抱歉。你误会我了。看到我的问题。在我的占位符中,我有“Naam”,但它应该显示带有红色星号的“Naam *”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-03
  • 1970-01-01
  • 2011-12-25
  • 2011-06-28
  • 2019-08-05
  • 2021-10-22
  • 2017-07-27
相关资源
最近更新 更多