美文网首页前端开发那些事儿JAVA
用css实现可编辑div输入框的placeholder效果

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

作者: 不会潜水的猫小喵 | 来源:发表于2020-03-24 18:13 被阅读0次

方法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 就可以解决这个问题。

相关文章

网友评论

    本文标题:用css实现可编辑div输入框的placeholder效果

    本文链接:https://www.haomeiwen.com/subject/kuhayhtx.html