textarea输入的内容保存后显示,保留换行过滤其他标签

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <textarea name="" id="" style="min-height: 100px;max-height: 200px;"></textarea>
    <div id="textTest"></div>
</body>
<script>
    var textarea = document.querySelector('textarea');

    textarea.addEventListener('input', function () {
        // console.log(this);

        this.style.height = 'auto'; // 先重置高度
        this.style.height = this.scrollHeight + 'px'; // 设置为内容的高度


        //***************start****************
        // 测试输入换行内容
        console.log(this.value);

        // 使用 textContent 来安全地处理用户输入
        const safeContent = document.createElement('div');
        safeContent.textContent = this.value;
        console.log(safeContent.innerHTML);
        
        // 将换行符替换为 <br> 标签
        const res = safeContent.innerHTML.replace(/\n/g, '<br>');
        console.log(res, '携带格式'); // 存数据库

        textTest.innerHTML = res; // 展示在页面
    });
</script>

</html>

textContent 比 innerText 性能好,并且识别是有区别的

查看:textContent vs innerText - linweiws - 博客园

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值