2016-04-30 75 views
2

我想弄明白,如果這甚至可能,從我所有的研究中看來都不是,但我希望100%確定。輸入元素上的圓形背景

我想在輸入元素內畫一個圓。該圓圈將是紅色,然後當它通過驗證時,它會變成綠色。我可以使用圖像很容易地做到這一點,但我試圖看看是否可以避免使用圖像來完成此操作。

我可以很容易地繪製圓用的div:

<div></div> 
div{ 
    width: 200px; 
    height: 200px; 
    border-radius: 50%; 
    background: red; 
} 

,但我不知道如何畫一個圓圈背景元素上。我正在研究可能使用:before:after元素,但這似乎不可能。

有沒有辦法完成這個?

+0

格相對於添加到輸入字段並在其中畫一個圓圈你需要使輸入透明。 – SEUH

回答

1

你可以使用pseudo-elementJQuery上驗證切換顏色(我用focus的演示(

$('input').on('focus', function() { 
 
    $(this).parent('div').addClass('active'); 
 
}); 
 
$('input').on('blur', function() { 
 
    $(this).parent('div').removeClass('active'); 
 
});
div { 
 
    position: relative; 
 
} 
 
div:before { 
 
    content: ''; 
 
    position: absolute; 
 
    left: 5px; 
 
    top: 50%; 
 
    width: 10px; 
 
    height: 10px; 
 
    border-radius: 50%; 
 
    background: blue; 
 
    transform: translateY(-50%); 
 
} 
 
div.active:before { 
 
    background: green; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div> 
 
    <input type="text"> 
 
</div>

3

您可以使用radial-gradient背景圖像來實現此功能,如下面的代碼片段所示。只要您只需支持現代瀏覽器,就不需要添加額外的元素。 Pseudo's不會與input元素一起工作,因爲它是一個自閉標籤。

經過測試,發現在Chrome(v51.0.2704.19 dev-m),Firefox(v45.0.2),Opera(v36)Edge,IE11,IE10中工作正常。 This approach would not work in IE9 and lower because support for CSS gradients is not there in those browsers

input { 
 
    background-image: radial-gradient(circle at center, red 4px, transparent 5px); 
 
    background-repeat: no-repeat; 
 
    background-size: 20px 100%; /* equal to the height */ 
 
    height: 20px; 
 
    padding-left: 20px; /* equal to background-size in X-axis */ 
 
} 
 
input:valid { 
 
    background-image: radial-gradient(circle at center, green 4px, transparent 5px); 
 
}
<input type='text' required/> 
 
<input type='text' value='Some text' required/>

+0

我支持IE9和以上,這不適用於IE9,只是測試 – Bojan

+1

@Bagzli:不,CSS漸變不適用於IE9。他們只能從IE10 +工作。您可以對IE10 +使用此方法,並對IE9使用圖像回退(或)使用包裝僞元素。我不認爲有任何替代方法。 – Harry