2015-02-09 58 views
0

如何在用户输入文本并点击后保持:focus的样式?用于输入的CSS伪选择器:用文字聚焦

input[type="text"]{ 
    background-color:transparent; 
} 
input[type="text"]:focus{ 
    background-color:white; 
    box-shadow: 3px 3px #red; 
} 
+1

'input [type =“text”] {...}' – 2015-02-09 05:04:19

+0

@VitorinoFernandes误会。编辑。 – softcode 2015-02-09 06:43:29

+0

当用户点击时,它会进入默认状态,即input [type =“text”] {..}'。在你的情况下,你需要编写一个脚本来为焦点添加类,以便即使焦点丢失时该类仍然保持。 – anpsmn 2015-02-09 06:53:47

回答

2

您需要使用Javascript。我所做的下面是添加一个类被点击输入时:

<style> 
input[type="text"]{ 
    background-color:transparent; 
} 
input[type="text"]:focus,input[type="text"].focus{ 
    background-color:white; 
    box-shadow: 3px 3px #red; 
} 
</style> 

<input type=text id=myinput> 

<script> 
// can't use the 'click' event because it'll wait for the user to release the mouse 
document.getElementById('myinput').addEventListener('mousedown',function() { 
    if(this.value) 
     this.className='focus'; 
},false); 
</script> 

小提琴:http://jsfiddle.net/99dgvebv/1/

编辑:

新增if(this.value)

+0

如果用户没有输入任何文字会发生什么?而小提琴不起作用 – softcode 2015-02-09 17:57:28

+0

我改变了它,加入'if(this.value)':) – 2015-02-10 20:31:29