用css实现可编辑div输入框的placeholder效果

方法1.输入框获取到光标时placeholder内容立刻消失

<!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="请输入内容"></div>
</body>
</html>

方法 2.输入框输入内容时placeholder内容消失,效果和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="请输入内容"></div>
</body>
</html>

两种效果唯一的差别就是处理 div 的内容为空的样式不一样,前者是在获取光标时设置伪元素 ::before 的内容为空,后者是在获取光标时设置 div 的内容为空,根据需求选择使用就行。

需要注意的地方:目前发现第二种情况的实现方式在 window10 的 Edge 浏览器下会有一个小问题,输入框获取光标时,光标会显示在 placeholder 内容的后面,虽然不影响使用,但是体验不是很好,这个时候只要把伪元素 ::before 改为 ::after 就可以解决这个问题。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容