但是你这个代码 实际上文字超出并没有显示红色框体
时间: 2023-08-06 09:09:41 浏览: 64
非常抱歉,我在之前的回答中犯了一个错误。正确的代码应该是将文本框的 `borderColor` 属性设置为红色,而不是 `backgroundColor`。
以下是修正后的代码:
```javascript
var myInput = document.getElementById('myInput');
myInput.oninput = function() {
var maxLength = parseInt(this.getAttribute('maxlength'));
var currentLength = this.value.length;
if (currentLength > maxLength) {
this.style.borderColor = 'red';
} else {
this.style.borderColor = '';
}
};
```
请注意,这段代码只会在文本框中输入内容时进行检测。如果你需要在文本框初始化时就检测文本框的内容长度,你可以在页面加载完成时执行类似的代码。
相关问题
怎么限制文本框字数并且超出显示红色框体
你可以按照以下步骤来实现文本框字数限制并超出时显示红色框体:
1. 在 HTML 中定义一个文本框,例如:
```html
<input type="text" id="myInput" maxlength="20">
```
其中,id 属性用于标识该文本框,maxlength 属性用于限制文本框中可输入的字符数。
2. 在 JavaScript 中获取该文本框,并绑定 oninput 事件。在该事件处理函数中,检查文本框中的字符数是否超过了限制,如果超过则将文本框的边框颜色设置为红色,否则设置为默认颜色。示例代码如下:
```javascript
var myInput = document.getElementById('myInput');
myInput.oninput = function() {
var maxLength = parseInt(this.getAttribute('maxlength'));
var currentLength = this.value.length;
if (currentLength > maxLength) {
this.style.borderColor = 'red';
} else {
this.style.borderColor = '';
}
};
```
在上面的示例代码中,我们首先获取了 id 为 myInput 的文本框,并绑定了 oninput 事件。在事件处理函数中,我们获取了文本框的 maxlength 属性值和当前输入的字符数,然后根据这两个值来判断是否超过了限制。如果超过了限制,就将文本框的边框颜色设置为红色,否则将边框颜色设置为默认值。
留言文字显示效果超出留言框外面去是什么问题
这个问题一般是由于留言框的父容器没有设置合适的 CSS 样式导致的。我们可以尝试通过以下几种方式解决:
1. 增加留言框的宽度,使其能够容纳更多的文字。
2. 将留言框的 CSS 样式中的 `box-sizing` 属性设置为 `border-box`,这样留言框的宽度就包括了边框和内边距。
3. 父容器的 CSS 样式中可以尝试设置 `overflow: hidden`,这样超出部分就会被隐藏。
4. 父容器的 CSS 样式中可以尝试设置 `word-wrap: break-word`,这样当文字超出容器宽度时,会自动换行。
您可以根据具体情况选择上述解决方法中的一种或多种进行尝试。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)