quest for the ultimate inline wysiwyg using jQuery
I'm no jQuery guru but I'm trying my best anyway - in the name of my quest for inline wysiwyg.
I've seen 'Aloha' but I rather not depend on buggy HTML5 features that's far from supported on all platforms.
I also dismissed the iframe and textarea solutions and decided to "fake" the text cursor and other text-input behavior directly inside the target DIV.
This might have been a mistake, I'm not sure yet.
My code should keep track of currently active DIV for editing, insert SPAN tags wrapping each character (nested tags omitted) and use those span tags onclick event to "move" the fake text cursor. I try to accomplish this by selecting the characted that was clicked, then appending the cursor-div after that.
开发者_StackOverflow社区Later on I'll add keyboard listeners but for now I'd be happy if I could get the "cursor" moving when I click around inside the active DIV.
Anyone with some skills and a spare half hour to help me work on this would be awsome, I'm struggling by myself and it's a miracle that I've gotten this far.
The code can be seen and tested on: http://jsfiddle.net/Zn5qD/
Any help appreciated!!
Why are you trying to reinvent the wheel, and in a such primitive way? Microsoft designed and implemented designMode
and contentEditable
attributes for this reason; to enable developers to create rich text editors.
With just a single line of code you can make your elements editable, and it works like a charm in all major browsers (IE 5.5+, FF 3+, Opera 9+, Safari 3+, Chrome).
$(".editable").attr("contentEditable", true);
To take it a step further we can bind the focus and blur events as a way to detect when the element enters the editable state. By comparing the contents of the elements on blur with a copy that was saved to the private data storage, we can detect any changes that was made to the element.
$(".editable").attr("contentEditable", true).bind({
focus: function(e){
var $this = $(this);
// Save the current content to data storage
// This so we can use it to detect if any changes were made
$this.data("content", $this.html());
},
blur: function(e){
var $this = $(this);
if ($this.data("content") !== $this.html()) {
// Content was changed so we can use ajax to save it
}
}
});
I took the liberty to modify your fiddle with the above example: http://jsfiddle.net/mekwall/Zn5qD/2/
If you want to know more about the contentEditable
and designMode
attributes you should check out this article: http://blog.whatwg.org/the-road-to-html-5-contenteditable
精彩评论