天天看點

DIV實作CSS 的placeholder效果

placeholder 是HTML5中input的屬性,但該屬性并不支援除input以外的元素

但我們可以使用Css before選擇器來實作完全相同的效果

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Div+placeholder</title>
	<style>
	.rich{
	    color:balck;
	    width:100px;
	    height:100px;
	    border: 1px solid red;
	    margin: 20px 50%;
	}
	/*為空時顯示 element attribute content*/
	.rich:empty:before{
	    content: attr(placeholder);   /* element attribute*/
	    /*content: 'this is content';*/
	    color:#red;
	}
	/*焦點時内容為空*/
	.rich:focus:before{
	    content:none;
	}
	</style>
</head>
<body>
	<div class='rich' contenteditable="true" placeholder='當 element 内容為空時,我就會出現'></div>
</body>
</html>
      

  

效果:

DIV實作CSS 的placeholder效果

參考:

HTML5 placeholder

CSS :before 選擇器

線上Demo:DIV實作css placeholder效果 

From WizNote

css