仿微信文本框,自动换行,动态高度,最大四行后滚动

仿微信文本框,自动换行,动态高度,最大四行后滚动

原理:

js监听textarea实时变化值,将textarea内容插入到一个和textarea相同大小的div中,且各属性相同,高度除外;之后将根据div的高度来给textarea的高度赋值,超出四行的高度时不再给textarea赋值;当监听到textarea内容只有4个回车符号时,截断内容;注意当textarea最后字符为回车时特殊处理高度。

1.html

<div class="hiddenContent"></div>
<textarea type="text" id="MsgContent" name="textareaname" maxlength="300" rows="1" cols="1" placeholder="请在此留言……"></textarea>

2.css

*{
	margin: 0;
	padding: 0;
	box-sizing: border-box;
}

textarea,.hiddenContent {
	font-family: "microsoft yahei";
	font-size: 30px;
	color: #333333;
	line-height: 40px;
	padding: 10px;
	width: 100%;
	resize: none;
	word-break: break-all;
	border-radius: 6px;
}

textarea {
	max-height: 182px;
	min-height: 62px;
	outline: none;
}

.hiddenContent {
	position: fixed;
	bottom: 0;
	left: 0;
	height: auto;
	z-index: 9999;
	border: 1px solid #EEEEEE;
}

3.js

function patch(re, s) {
	re = eval("/" + re + "/ig")
	return s.indexOf(re.source) > -1 ? s.match(re).length : 0;
}

$('#MsgContent').on("input propertychange", function() {
	var content = $(this).val();
	var data = content.replace(/\n/g, "<br>");
	var num = patch('<br>', data);
	if (content.length >= 3 && num >= 3 && content.length == num) {
		$(this).val(content.substring(0, 3))
		$(this).height((num + 1) * 40)
	} else {
		$(".hiddenContent").html(data)
		if ($(this)[0].scrollHeight <= 200) {
			setTimeout(function() {
				var lastStr = content.substring(content.length - 1, content.length).replace(/\n/g, "<br>")
				if (patch('<br>', lastStr)) {
					$('#MsgContent').height($(".hiddenContent").height() + 40)
				} else {
					$('#MsgContent').height($(".hiddenContent").height())
				}
			}, 10)
		}
	}
})

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Let dreams fly

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值