需求 实现一个输入框显示文本的字数,并且设置字数限制,当文本中没有内容或字符串长度超出限制,则不能点击确定按钮。
<div class="input-content">
<div class="pt-2 rounded-tl-xl rounded-tr-xl bg-blue-100">
<div class="px-4 pb-2 flex justify-between h-8 items-center">
<span class="text-gray-800 font-semibold text-sm">请输入文本</span>
</div>
<div class="h-2 rounded-tl-xl rounded-tr-xl bg-white"></div>
</div>
<div class="px-4 pb-11">
<textarea id="text-input" v-model="text" placeholder="请输入文本,建议使用简短的陈述句。"
class="input-textarea"></textarea>
<div class="absolute inset-x-0 bottom-0 flex items-center justify-between mx-4 mt-2 mb-2">
<div id="char-count" class="px-2.5 py-px text-xs leading-5
rounded-md inline-flex items-center flex-shrink-0 text-gray-800 bg-gray-100
!text-gray-500 opacity-50">0<span class="text-gray-300 mx-0.5">/</span>200
</div>
<el-button size="medium" type="primary" :disabled="!canClick"
:loading="testLoading" round @click="handleTest">确定</el-button>
</div>
</div>
</div>
computed: {
canClick() {
return this.text.length > 0 && this.text.length <= 200;
},
}
data() {
return {
testLoading: false,
text: '',
}
}
mounted() {
const textarea = document.getElementById('text-input');
const charCount = document.getElementById('char-count');
textarea.addEventListener('input', function () {
const text = textarea.value;
const count = text.length;
charCount.textContent = count + '/200';
if (count > 200) {
textarea.value = text.slice(0, 200); // 截断输入文本,只保留前200个字符
charCount.style.color = 'red'; // 如果超过200个字符,可以显示为红色提示
} else {
charCount.style.color = ''; // 恢复默认颜色
}
});
},
.input-content {
position: relative;
border-radius: 0.75rem;
border-width: 1px;
--tw-border-opacity: 1;
border-color: rgb(28 100 242 / var(--tw-border-opacity));
}
.input-textarea {
height: 220px !important;
width: 100% !important;
resize: none !important;
border-style: none !important;
font-size: .875rem !important;
line-height: 1.25rem !important;
font-weight: 400 !important;
--tw-text-opacity: 1 !important;
color: rgb(55 65 81/ 1) !important;
caret-color: #1c64f2 !important;
outline: none;
}