經(jīng)常有需要是,在用戶輸入錯(cuò)誤的時(shí)候給用戶進(jìn)行提示,一般我們可能會(huì)在input的下面隱藏一個(gè)span,來(lái)進(jìn)行提示,如果用dom操作它的text,這樣做算是比較麻煩的,操作的對(duì)象多,有沒(méi)有更加簡(jiǎn)單的方法呢?
css 的attr給出了這種可能,attr可以獲取某個(gè)元素的屬性值
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style type="text/css">
#inputBox {
position: relative;
}
#inputBox::after {
content: attr(tips);
position: absolute;
background: orange;
left: 0px;
top: 1.5em;
}
</style>
</head>
<body>
<!-- 目前 input 不支持before after -->
<div id="inputBox" tips="">
<input type="text" id="inputLine"/>
</div>
<script type="text/javascript">
//輸入錯(cuò)誤的時(shí)候 進(jìn)行提示
document.getElementById("inputLine").onblur = function(event) {
var target = event.target || event.srcElement;
var value= target.value;
var reg = /\w+@\w+\.\w{2,3}/;
if (!reg.test(value)) {
document.getElementById("inputBox").setAttribute("tips", "郵箱驗(yàn)證錯(cuò)誤");
}
}
</script>
</body>
</html>
Paste_Image.png
上面的做法還不是最好的,因?yàn)椴荒芗舆吙颍绻舆吙虻脑挘瑫?huì)有即使 tips沒(méi)有內(nèi)容的話,還是會(huì)有邊框顯示出來(lái)
有沒(méi)有更好一點(diǎn)的呢? 當(dāng)然是使用css的邊框選擇器了
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style type="text/css">
/*存在tips屬性的時(shí)候 inputBox才...*/
#inputBox[tips] {
position: relative;
}
#inputBox[tips]::after {
content: attr(tips);
position: absolute;
border: 1px solid gray;
background: orange;
left: 0px;
top: 1.5em;
}
</style>
</head>
<body>
<!-- 目前 input 不支持before after -->
<div id="inputBox">
<input type="text" id="inputLine"/>
</div>
<div>aaaaa</div>
<script type="text/javascript">
//輸入錯(cuò)誤的時(shí)候 進(jìn)行提示
document.getElementById("inputLine").onblur = function(event) {
var target = event.target || event.srcElement;
var value= target.value;
var reg = /\w+@\w+\.\w{2,3}/;
if (!reg.test(value)) {
document.getElementById("inputBox").setAttribute("tips", "郵箱驗(yàn)證錯(cuò)誤");
}
}
document.getElementById("inputLine").onfocus = function(event) {
document.getElementById("inputBox").removeAttribute("tips");
}
</script>
</body>
</html>
通過(guò)對(duì)比發(fā)現(xiàn),只有在有對(duì)應(yīng)屬性的情況下,after才進(jìn)行對(duì)應(yīng)的顯示。 所以一開(kāi)始它是沒(méi)有border的
Paste_Image.png