jQuery Drag & Drop into a Text Area

后端 未结 1 951
广开言路
广开言路 2020-12-30 09:27

Using jQuery, and looking to let user drag a placeholder into a text area.

Each placeholder is a which has a class=\'placeholder\'

相关标签:
1条回答
  • 2020-12-30 09:59

    I don't think you can use the textarea directly as droppable thus I made a little hack which on drag-start positions a div directly over the textarea. The div is the actual droppable which then inserts the text of the draggable into the textarea

    Check here for a demo

    http://jsbin.com/egefi (http://jsbin.com/egefi/edit for the code)

    It inserts at current textcaret position I don't think inserting at current mouse cursor position is even possible.

    function insertAtCaret(area, text) {
        //... adapted from http://www.scottklarr.com/topic/425/how-to-insert-text-into-a-textarea-where-the-cursor-is/
    }
    
    $(document).ready(function() {
        var options = {
            accept: "span.placeholder",       
            drop: function(ev, ui) {
                insertAtCaret($("textarea#main_text").get(0), ui.draggable.eq(0).text());
            }
        };
    
        $("span.placeholder").draggable({
            helper:'clone',
            start: function(event, ui) {
                var txta = $("textarea#main_text");
                $("div#pseudodroppable").css({
                    position:"absolute",
                    top:txta.position().top,
                    left:txta.position().left,
                    width:txta.width(),
                    height:txta.height()
                }).droppable(options).show();
            },
            stop: function(event, ui) {
                $("div#pseudodroppable").droppable('destroy').hide();
            }
        });
    });
    
    0 讨论(0)
提交回复
热议问题