Format contentEditable element as you type
I basically want to do something very simple: I want the user to type in a tweet, and after 140 characters, I want the text that will be cut off to be greyed out. Should be simple, right?
I'm using the contentEditable property for the formatting. On the keyup
event, I check if the text is too long, and move the extra chars into a <span>
if this is the case. However, the selection gets lost on the way.
I've already tried many things (including this), but nothing worked - can you help me? I guess it would help me the most if you could give a working example.
I took this on because I was interested. It's an annoyingly large amount of code, but that's just how it is. My new version doesn't use Rangy's saveSelection() but does use its cross-browser Range support for IE compatibility. It's too much code to post here, so I'll just link to the jsfiddle: http://jsfiddle.net/timdown/g7KJ5/9/
I emailed joey already, but give this a look:
https://gist.github.com/746962
I've tried a new approach now and this is what I came up with:
$.fn.softlimit = function(maxChars, wrapElement, wrapAttributes) {
var lastHTML, that = this[0];
setInterval(function() {
//Only trigger on change
if (lastHTML == that.innerHTML) return;
lastHTML = that.innerHTML;
// Save the selection
var savedSel = rangy.saveSelection();
// Strip HTML and extract rangy markers
var markers = [ ], text = '', htmlPos = 0;
function escapeForHTML(text) {
return text.replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"');
}
function processNode(node) {
if (node.nodeType == 3)
text += escapeForHTML(node.nodeValue);
else if (node.nodeName == 'SPAN' && node.id && node.id.indexOf('selectionBoundary_') === 0)
markers.push({ index: text.length, html: node.outerHTML });
else
for (var i = 0; i < node.childNodes.length; ++i)
processNode(node.childNodes[i]);
}
processNode(that);
// Do formatting
var getOffset, markerOffset = 0;
if (text.length > maxChars) {
var startTag = '<' + wrapElement + ' ' + wrapAttributes + '>';
var endTag = '</' + wrapElement + '>';
text = text.substr(0, maxChars) + startTag + text.substr(maxChars) + endTag;
getOffset = function(index) {
if (index > maxChars) return startTag.length;
else return 0;
};
}
else
getOffset = function() { return 0; };
// Re-inject markers
for (var i = 0; i < markers.length; ++i) {
var marker = markers[i];
var index = marker.index + getOffset(marker.index) + markerOffset;
text = text.substr(0, index) + marker.html + text.substr(index);
markerOffset += marker.html.length;
}
that.innerHTML = text;
// Restore the original selection
rangy.restoreSelection(savedSel);
}, 20);
return $(this);
};
Thanks to @Tim Down for the hint with the markers, that was the crucial clue!
精彩评论