遇到以下问题。
我必须在textarea上限制用户每行的最大字符数,但是当包含垂直滚动条时,似乎cols不起作用:
.textarea1 {
resize: none;
font-family: monospace;
}

When no scrollbar is visible, it works fine using 50 chars.
<br />
<textarea class="textarea1" cols="50" rows="3">123456789!123456789!123456789!123456789!123456789!</textarea>
<br />
In this case, when the scrollbar is visible, at least 3 chars go to the next line.
<textarea class="textarea1" cols="50" rows="3">1234567890123456789!1234567890123456789!123456789!123456789!1234567890123456789!1234567890123456789!123456789!1234567890123456789!123456789!123456789!123456789!123456789!123456789!123456789!123456789!</textarea>
<br />
In this case, when I use 10 chars, I can fit an extra 1 char on each line.
<br />
<textarea class="textarea1" cols="10" rows="3">123456789!</textarea>
<br />
In this case, scrollbar visible, 1 char go to the next line.
<br />
<textarea class="textarea1" cols="10" rows="3">123456789!123456789!123456789!123456789!123456789!</textarea>
&#13;
我考虑过计算textarea的宽度,例如这个伪代码。
scrollbarWidth + textareaBorderWidth + (nChars * singleCharWidth)
但是没有骰子,它使用较小的线条(10个字符)太大而使用50个字符时太小。
需要支持IE10 +,所以ch单位是不行的。除了对IE11的支持之外,至少可以说是狗。
任何解决方案?
答案 0 :(得分:0)
这对你有用。但是只在Chrome上测试过它。
function scrollbarVisible(element) {
return element.scrollHeight > element.clientHeight;
}
$.each($("textarea"), function(index, value){
var cols = value.getAttribute("cols");
if (cols > 0){
if (scrollbarVisible(value)){
cols = parseInt(cols) + 3;
}
$(value).css("width", cols + "ch");
}
})
.textarea1 {
resize: none;
padding: 0;
display: block;
line-height: 1;
resize: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
When no scrollbar is visible, it works fine using 50 chars.
<br />
<textarea class="textarea1" cols="50" rows="3">123456789!123456789!123456789!123456789!123456789!</textarea>
<br />
In this case, when the scrollbar is visible, at least 3 chars go to the next line.
<textarea class="textarea1" cols="50" rows="3">1234567890123456789!1234567890123456789!123456789!123456789!1234567890123456789!1234567890123456789!123456789!1234567890123456789!123456789!123456789!123456789!123456789!123456789!123456789!123456789!</textarea>
<br />
In this case, when I use 10 chars, I can fit an extra 1 char on each line.
<br />
<textarea class="textarea1" cols="10" rows="3">123456789!</textarea>
<br />
In this case, scrollbar visible, 1 char go to the next line.
<br />
<textarea class="textarea1" cols="10" rows="3">123456789!123456789!123456789!123456789!123456789!</textarea>