簡體   English   中英

Html僅在表單中的輸入占位符字段中的顏色(*)符號

[英]Html Color only (*) symbol in input placeholder field in form

我有以下代碼:

<input id="firstName" name="fname" type="text" maxlength="50" placeholder="First Name *" required>

如何將占位符值中的(*)符號着色為紅色而不將其他文本着色(作為名字文本)?

任何幫助深表感謝!

謝謝!

一個可能的選擇可能是使用:valid偽類用於所需的 <input>以使絕對定位的兄弟元素消失 - 它被用作輸入下的占位符。

因此,我們可以在絕對定位元素上使用::before / ::after偽元素來更改偽占位符的顏色。

 .input-wrapper { display: inline-block; position: relative; } .input-wrapper input { background: transparent; border: 1px solid #999; } .input-wrapper input:valid + .placeholder { display: none; } .input-wrapper .placeholder { position: absolute; top: 1px; left: 2px; z-index: -1; } .input-wrapper .placeholder::before { content: attr(data-placeholder); color: #999; } .input-wrapper .placeholder::after { content: " *"; color: tomato; } 
 <div class="input-wrapper"> <input id="firstName" name="fname" type="text" maxlength="50" required> <span class="placeholder" data-placeholder="First Name"></span> </div> 

值得注意的是:valid IE10 +支持:valid偽類。

不幸的是,無法更改輸入中某些文本的顏色:(您可以嘗試使用一個contenteditable div:

<div class="input" contenteditable>First Name <span style="color:red;">*</span></div>

然后,您必須使用JS添加和刪除占位符:

$(function(){
    $('.input').focus(function(){
        $(this).html('');
    });
    $('.input').blur(function(){
       if($(this).html()=='') this.innerHTML='First Name <span style="color:red;">*</span>';
    });
});

JSFiddle演示

你可能不會那樣。 執行此操作的最佳方法是這樣的答案: 輸入標記中的多種字體顏色

實質上,第二個div放在輸入字段上,允許顏色變化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM