likes
comments
collection
share

使用 div 实现 input、textarea 输入框,并支持 placeholder 属性(解决浏览器兼容问题)

作者站长头像
站长
· 阅读数 7

解决这个问题的初衷:在做文本编辑器时,系统自带的 textarea火狐 浏览器中回车不会进行换行,被显示成了空格,找了好几种方案没解决,试了下 div 实现 inputtextarea 的方式,发现可以完美解决这个问题

一、div 实现 textarea

使用 div 实现 input、textarea 输入框,并支持 placeholder 属性(解决浏览器兼容问题)

1、给 div 添加 contenteditable="true" 属性,使 div 元素变成用户可编辑。

2、给 div 添加 resize: both; 样式,使 div 可以被用户调整尺寸,注意:同时需要设置 overflow: auto; 样式,因为 resize 样式不适用于 overflow: visible; 的块,不然 resize 不会生效,如果不需要支持手动拖拽输入框,不加就行

resize 支持输入框拉伸的属性:vertical(垂直拉伸)horizontal(水平拉伸)both(垂直与水平拉伸)

3、增加一个 placeholder 属性,通过 CSS 控制显示。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    /* 输入框 */
    .dzm-textarea {
      padding: 5px;
      border: 1px solid red;
    }
    /* 输入框为空时显示 placeholder */
    .dzm-textarea:empty:before {
      content: attr(placeholder);
      color: red;
    }
    /* 输入框获取焦点时移除 placeholder */
    .dzm-textarea:focus:before {
      content: none;
    }
  </style>
</head>
<body>
  <!-- textarea -->
  <div class="dzm-textarea" contenteditable="true" placeholder="请输入内容" style="resize: both; overflow: auto;"></div>
</body>
</html>

二、div 实现 input

使用 div 实现 input、textarea 输入框,并支持 placeholder 属性(解决浏览器兼容问题)

1、给 div 添加 contenteditable="true" 属性,使 div 元素变成用户可编辑。

2、给 div 添加一个 onkeydown 事件,然后禁止 回车换行

3、增加一个 placeholder 属性,通过 CSS 控制显示。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    /* 输入框 */
    .dzm-input {
      padding: 5px;
      border: 1px solid red;
    }
    /* 输入框为空时显示 placeholder */
    .dzm-input:empty:before {
      content: attr(placeholder);
      color: red;
    }
    /* 输入框获取焦点时移除 placeholder */
    .dzm-input:focus:before {
      content: none;
    }
  </style>
</head>
<body>
  <!-- input -->
  <div class="dzm-input" contenteditable="true" placeholder="请输入内容" onkeydown="myFunction()"></div>
  <script>
    // 禁止回车换行
    function myFunction(){
      if (window.event && window.event.keyCode == 13) {
        window.event.returnValue = false;
      }
    }
  </script>
</body>
</html>
转载自:https://juejin.cn/post/7033224792291409934
评论
请登录