开发者

Add form element functionality to contenteditable div

开发者 https://www.devze.com 2023-01-04 11:38 出处:网络
I use the MooTools Javascript library. And this library give a couple of really useful functions here: http://mootools.net/docs/more/Element/Element.Forms

I use the MooTools Javascript library. And this library give a couple of really useful functions here: http://mootools.net/docs/more/Element/Element.Forms

The problem is that this functions only work for 'form' elements like textarea, etc.

Now i am making a online editor and for the editor it self i use a div element and the content editable functionality.

When i want to use functions like getCaretPosition in the m开发者_运维问答ootools (more) library this line gets called:

var range = this.getDocument().selection.createRange();

But than i get this error:

this.getDocument().selection is undefined

It seems that only form elements have this selection object (on this document :S ?).

Is there a way to add the form functionality to the div (or all) element(s) ?


it won't work that easily, I am afraid. look at the source code

for example, setSelectionRange has two assertions, 1: it has type == "text" (hence, an input) or 2: it has a .value property it can read. if you apply that to an element that lacks either, it just won't work.

you can possibly look for ideas elsewhere - for example this david walsh document selection snippet may be useful:

http://davidwalsh.name/text-select-widget

he's simply doing:

var getSelection = function() {
    return $try(
        function() { return window.getSelection(); },
        function() { return document.getSelection(); },
        function() {
            var selection = document.selection && document.selection.createRange();
            if(selection.text) { return selection.text; }
            return false;
        }
    ) || false;
};

good luck - here is a very rudimentary example that i put together hastily, it provides getting selection and possible caret position (based upon last char of selection) as offset of the parent element - http://www.jsfiddle.net/82czp/1/


I found this functionality in a Javascript project called CodeMirror ( http://marijn.haverbeke.nl/codemirror/ , also used in jsfiddle). Great project!

0

精彩评论

暂无评论...
验证码 换一张
取 消