http://learn.javascript.ru/play/nj2d2b
С range никогда не работал, поэтому взял кусок кода у
bes`а.
<!DOCTYPE HTML>
<html>
<head>
<title>Test</title>
<style type="text/css">
div[contenteditable] {
border: 1px solid #AAA;
color: #AAA;
height: 20px;
line-height: 20px;
margin: 5px 0;
overflow: hidden;
text-indent: 3px;
white-space: nowrap;
width: 200px;
}
</style>
<script type="text/javascript">
window.addEventListener('DOMContentLoaded', function() {
var divs = document.querySelectorAll('div[contenteditable]');
[].forEach.call(divs, function(self) {
var maxLength = self.dataset.max;
if(maxLength) {
self.addEventListener('input', function(e) {
if(this.innerHTML.length > maxLength) {
var selection = window.getSelection(),
range = selection.getRangeAt(0),
pos = range.endOffset;
this.innerHTML = this.innerHTML.substr(0, maxLength);
try {
range.setStart(range.startContainer , pos);
} catch (e) {
range.setStart(range.startContainer , pos - 1);
}
selection.removeAllRanges();
selection.addRange(range);
}
}, false);
}
});
});
</script>
</head>
<body>
<div contenteditable="true" data-max="20"></div>
<div contenteditable="true" data-max="30"></div>
</body>
</html>