js限定文本框里面的输入字数

限定文本框里面的输入字数

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            padding: 0px;
            margin: 0px;
        }

        .box {
            width: 500px;
            margin: 0 auto;
            padding-top: 100px;
        }

        .div {
            /* 清除掉文本域的默认边框颜色 */
            outline: none;
            width: 500px;
            height: 300px;
            border: 1px solid red;
            float: right;
            /* 文本域禁止拖拽属性 */
            resize: none;
        }

        p {
            border: 1px solid rebeccapurple;
            width: 150px;
            height: 20px;
            float: right;
        }

        button {
            float: right;
            background-color: orange;
            color: white;
            padding: 10px, 20px;
            width: 60px;
            height: 30px;
            ;
        }
    </style>
</head>

<body>
    <div class="box">
        <p class="pp">已经输入0个字</p>
        <form action="">
            <textarea name="" class="div" cols="30" rows="10" value=""></textarea>
        </form>
        <button>发布</button>
    </div>
    <script>
        var div = document.querySelector(".div");
        var pp = document.querySelector(".pp");
        div.oninput = function () {
            var le = div.value.length;
            console.log(le);
            if (le <= 140) {
                div.style.color = "black";
                pp.innerHTML = "已经输入" + le + "个字"
            } else if (le > 140 && le <= 180) {
                div.style.color = "red";
                pp.innerHTML = "还可以输入" + (180 - le) + "个字"
            } else if (le > 180) {
                // alert("你已经超过最大限制了");
                div.value = div.value.substring(0, 180);
                pp.innerHTML = "还可以输入0个字"
            }
        }   
    </script>
</body>

</html>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值