我该如何让我的字符计数器不出现在输入框中呢?

我想知道为什么每当我将 <input> 标签切换到 <p> 标签时,我的字符计数器就不会出现根本不。我希望 Characters remaining: 部分不要位于 <input> 标记内。我尝试了很多方法来解决这个问题,但都碰壁了,我只需要另一双眼睛来看看这个问题。

我做错了什么以及如何解决这个问题? JSFiddle 提供供参考。

https://jsfiddle.net/2b38k9zt/

var txtBoxRef = document.querySelector("#txtBox");

var counterRef = document.querySelector("#counterBox");

txtBoxRef.addEventListener("keydown",function(){

    var remLength = 0;

    remLength = 0 + parseInt(txtBoxRef.value.length);

    if(remLength < 0) {

        txtBoxRef.value = txtBoxRef.value.substring(0, 200);

        return false;

    } else if(remLength > 200) {

        counterRef.style.color = "red";

    }

    counterRef.value = "Characters remaining: " + remLength + "/200";

},true);

<textarea style="width: 600px;" id="txtBox"></textarea>

<input type="text" id="counterBox"/>


慕后森
浏览 116回答 2
2回答

PIPIONE

将您的输入设置为 p 元素并更改此行counterRef.value&nbsp;=&nbsp;"Characters&nbsp;remaining:&nbsp;"&nbsp;+&nbsp;remLength&nbsp;+&nbsp;"/200";到counterRef.innerHTML&nbsp;=&nbsp;"Characters&nbsp;remaining:&nbsp;"&nbsp;+&nbsp;remLength&nbsp;+&nbsp;"/200";

LEATH

input 标签具有 value 属性,而 p 标签应使用 textContent 属性:var txtBoxRef = document.querySelector("#txtBox");var counterRef = document.querySelector("#counterBox");var pRef = document.querySelector("#pBox");txtBoxRef.addEventListener("keydown",function(){&nbsp; &nbsp; var remLength = 0;&nbsp; &nbsp; remLength = 0 + parseInt(txtBoxRef.value.length);&nbsp; &nbsp; if(remLength < 0) {&nbsp; &nbsp; &nbsp; &nbsp; txtBoxRef.value = txtBoxRef.value.substring(0, 200);&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; } else if(remLength > 200) {&nbsp; &nbsp; &nbsp; &nbsp; counterRef.style.color = "red";&nbsp; &nbsp; }&nbsp; &nbsp; pRef.textContent = "Characters remaining: " + remLength + "/200";},true);<textarea style="width: 600px;" id="txtBox"></textarea><input type="text" id="counterBox"/><p id='pBox'></p>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5