一、实现效果
1、未输入内容时
2、输入少于50
字的内容时
3、输入大于等于50
字的内容时
二、实现代码
代码里【1】、【2】、【3】分别对应:
- 【1】=》
textarea
文本框输入字数限制- 【2】=》
textarea
文本框输入字数显示- 【3】=》 若输入文本长度 大于等于 文本框输入字数限制长度,则【
50/50
】变为红色
textareaBox.jsx
:
import React from 'react';
class InputBox extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
// 【2】、JS textarea文本框输入字数显示
const el = document.getElementById('textarea'); // 获取到textarea输入框的dom节点
// 实时监听文本框输入内容
el.addEventListener('input', () => {
const value = el.value; // 获取到输入的文本内容
const valueLength = value.length; // 获取到输入文本的长度
document.getElementById('textLength').innerHTML = valueLength; // 将输入文本长度在页面上实时展示出来
// 【3】、JS 若输入文本长度 大于等于 文本框输入字数限制长度,则【50/50】变为红色
const totalLength = document.getElementById('totalLength').innerHTML; // 获取到文本框输入字数限制长度
if(valueLength == totalLength){
document.querySelector('.words').style.color = 'red'; // 设置css样式
} else {
document.querySelector('.words').style.color = '#b3b3b3';
}
});
}
render() {
return (
<div>
{/* 【1】、JS textarea文本框输入字数限制【50字 -> maxLength="50"】*/}
<div className="textareaBox">
<textarea name="" className="textarea" id="textarea" maxLength="50" placeholder="心愿精选后,将对所有人可见"></textarea>
<div className="words"><span id="textLength">0</span>/50</div>
</div>
</div>
);
}
}
export default InputBox;
textareaBox.less
:
/** 修改textarea文本框的placeholder的样式 */
textarea::-webkit-input-placeholder { /* WebKit browsers */
color: #b3b3b3;
}
textarea:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
color: #b3b3b3;
}
textarea::-moz-placeholder { /* Mozilla Firefox 19+ */
color: #b3b3b3;
}
textarea:-ms-input-placeholder { /* Internet Explorer 10+ */
color: #b3b3b3;
}
.textareaBox {
width: 688px;
height: 336px;
left: 31px;
top: 102px;
position: absolute;
}
.textarea {
width: 100%;
height: 100%;
left: 0;
top: 0;
position: absolute;
border-radius: 20px;
background-color: #fff;
border: 0;
padding: 40px;
box-sizing: border-box;
font-size: 28px;
line-height: 28px;
color: #1f1f1f;
outline: none;
}
.words {
right: 48px;
bottom: 27px;
position: absolute;
font-size: 28px;
line-height: 30px;
color: #b3b3b3;
}
本文含有隐藏内容,请 开通VIP 后查看