方法1.輸入框獲取到光標時placeholder內(nèi)容立刻消失
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<style>
.edit-box {
width: 200px;
height: 200px;
border: 1px solid #000;
outline: none;
overflow: auto;
}
.edit-box:empty::before {
content: attr(placeholder);
color:#ccc;
}
.edit-box:focus:before {
content:none;
}
</style>
</head>
<body>
<div class="edit-box" contenteditable="true" placeholder="請輸入內(nèi)容"></div>
</body>
</html>
方法 2.輸入框輸入內(nèi)容時placeholder內(nèi)容消失,效果和input叛溢、textarea效果一樣
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<style>
.edit-box {
width: 200px;
height: 200px;
border: 1px solid #000;
outline: none;
overflow: auto;
}
.edit-box:empty::before {
content: attr(placeholder);
color:#bbb;
}
/*不一樣的地方*/
.edit-box:focus {
content:none;
}
</style>
</head>
<body>
<div class="edit-box" contenteditable="true" placeholder="請輸入內(nèi)容"></div>
</body>
</html>
兩種效果唯一的差別就是處理 div 的內(nèi)容為空的樣式不一樣蹈集,前者是在獲取光標時設(shè)置偽元素 ::before 的內(nèi)容為空,后者是在獲取光標時設(shè)置 div 的內(nèi)容為空雇初,根據(jù)需求選擇使用就行拢肆。
需要注意的地方:目前發(fā)現(xiàn)第二種情況的實現(xiàn)方式在 window10 的 Edge 瀏覽器下會有一個小問題,輸入框獲取光標時靖诗,光標會顯示在 placeholder 內(nèi)容的后面郭怪,雖然不影響使用,但是體驗不是很好刊橘,這個時候只要把偽元素 ::before 改為 ::after 就可以解決這個問題鄙才。