【问题标题】:Drop "draggable" into Handsontable cell将“可拖动”拖放到 Handsontable 单元格中
【发布时间】:2014-01-15 03:27:14
【问题描述】:

我厌倦了使用带有 jQ​​uery UI 拖放功能的 Handsontable jQuery 模块,但没有成功。我找到了一些带有 insertAtCaret 函数的代码,但我在使用 Handsontable 时遇到了麻烦。 我希望能够将元素从 Handsontable 表外部拖放到单元格中。我知道,我必须以某种方式更新单元格...... 请帮忙...

代码:

$.fn.insertAtCaret = function (myValue) {
    return this.each(function(){
        //IE support
        if (document.selection) {
            this.focus();
            sel = document.selection.createRange();
            sel.text = myValue;
            this.focus();
        }
        //MOZILLA / NETSCAPE support
        else if (this.selectionStart || this.selectionStart == '0') {
            var startPos = this.selectionStart;
            var endPos = this.selectionEnd;
            var scrollTop = this.scrollTop;
            this.value = this.value.substring(0, startPos)+ myValue+ this.value.substring(endPos,this.value.length);
            this.focus();
            this.selectionStart = startPos + myValue.length;
            this.selectionEnd = startPos + myValue.length;
            this.scrollTop = scrollTop;
        } else {
            this.value += myValue;
            this.focus();
        }
    });
};

My JSFiddle with source

【问题讨论】:

    标签: javascript jquery jquery-ui-draggable handsontable


    【解决方案1】:

    insertAtCaret 代码并不是您在这种情况下真正需要的。您已经很好地处理了所需的事务 - 您需要在 drop 事件中使用 ui.draggable 元素来手动将一些文本添加到正确的单元格中。您只需要最后几步。

    现在,一个关键信息是 Handsontable 要你设置单元格数据通过坐标,这意味着你需要知道你要设置的东西的列和行, 只是有一个对实际 dom 元素的 javascript 引用。为此,我们可以使用jQuery's index method

    1. 找出拖放对象所在的单元格。
    2. 确定该单元格的列和行是什么。
    3. 使用 Handsontable 的 setDataAtCell 方法更改数据。

    Live Demo

    $("#excel_table").droppable({
        ...
        drop: function(event, ui) {
    
            // Get a reference to the handsontable instance
            var ht = $('#excel_table').handsontable('getInstance');
    
            // Hide the helper, so that we can use .elementFromPoint
            // to grab the item beneath the cursor by coordinate
            ui.helper.hide();
            var $destination = $(document.elementFromPoint(event.clientX, event.clientY));
    
            // Grab the parent tr, then the parent tbody so that we
            // can use their index to find the row and column of the
            // destination object
            var $tr = $destination.closest('tr');
            var $tbody = $tr.closest('tbody');
    
            var col = $tr.children().index($destination);
            var row = $tbody.children().index($tr);
    
            // Use the setDataAtCell method, which takes a row and
            // col number, to adjust the data                           
            ht.setDataAtCell(row, col, ui.draggable.text());
        },
        ...
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-05
      • 2013-01-27
      • 1970-01-01
      • 1970-01-01
      • 2013-04-17
      • 1970-01-01
      相关资源
      最近更新 更多