How to set max length for Span and Di开发者_开发百科v elements ?
There are the
max-height / max-width
CSS properties that will limit the width for block level elements (i.e. not span
s). Reference
Note that they are not supported by IE 6.
input
and textarea
html tags have maxlength attribute but div
and span
element don't have. To restrict user from entering more characters compare to maxlength in span or div element, you can do following using javascript
and jquery
:
You can add keydown
event listener on div
or span
element and add following functions in event listener.
1: Using javascript substring
method.
$("#div-element").on("keydown", function () {
var value = $("#div-element").val();
if (value.length > maxlength) {
$("#div-element").val(value.substring(0, maxlength));
}
}());
2: Returning false
on event.
$("#div-element").on("keydown", function () {
var value = $("#div-element").val();
if (value.length > maxlength) {
return false;
}
}());
These both have followup issues which should be handled as well ie substring
method change the cursor position, in keydown
method we need to check which key is pressed, otherwise it return false even on backspace or delete key.
When the word contained is too large the div or span may overflow:
<div style="width: 80px; overflow: hidden;" >hhhhhhheeeeeellllllllllooooo</div>
- You can wrap a span with a div. It will cut the content if there are no spaces in the text but it will prevent overflow from happening.
If long words are the problem a CSS3 solution could be:
style="width: 80; word-wrap: break-word;"
If you mesn width, then use css width properties:
<div style='max-width:100px'>Content</div>
<span style='max-width:100px; display:block;'>Content</span>
If you really mean length of content, You can't, in HTML. You need to use a piece of javascript to do this. Take a look at JQuery, it's really easy to do. It will boil down to something like:
$('#yourDivId').html().length
You mean max width?
max-width: ??px;
精彩评论