Handsontable 持久 CSS

Handsontable persistent CSS

根据这个问题 我正在使用自定义渲染器为我的单元格应用样式(粗体、斜体、下划线、字体大小、字体系列)。

正如上面问题的答案所建议的那样,我有一个对象的后备数组,每个对象代表我 table 中的每个单元格,具有自己的属性,以便渲染器知道要渲染什么(即粗体:真,斜体:假)。

但是,这似乎是一种笨拙的方法,因为当我插入 row/col 时,我也需要在后备数组中反映这一变化,以便我可以再次渲染它。这对我来说似乎太麻烦了,我无法想象没有更简单的方法来做到这一点(想象一下有一个完整的 100x100 table 自定义 CSS 并在开头插入一个 col) .

我的代码示例:

var myRenderer = function myRenderer(instance, td, row, col, prop, value, cellProperties) {
    Handsontable.renderers.TextRenderer.apply(this, arguments);

    var id = row+","+col;
    var result = $.grep(arr, function(e){ return e.id == id; });
    if (result[0] == undefined) {
        return;
    }
    if (result[0].bold) {
        var cell = $("table tr:eq(" + row + ") td:eq(" + col + ")");
        cell.css("font-weight", "bold");
    }
    ...
}

有没有一种更简单的方法可以将 CSS 样式 直接 存储在 handsontable 实例中,这样我就不必有后备数组了?

我发现 CSS classes 在单元元数据中是持久的。这意味着应该可以为每种样式设置一个 class(或在运行时以编程方式创建它们)并将其附加到单元格 classes.

style.css

.myBold {
    font-weight: bold;
}

script.js

function addClass(row, col, mClass) {
    // row is row of the cell, col is column of the cell

    var cell = $("table tr:eq(" + row + ") td:eq(" + col + ")");

    // OPTIONAL - remove highlights from cells if you selected them by dragging
    cell.removeClass("area");
    cell.removeClass("highlight");
    cell.removeClass("current");
    // END OPTIONAL

    var classes = cell.attr("class");
    classes += mClass; //"myBold" in this case

    var hotCells = hot.getSettings().cell; //hot is Handsontable instance

    var containsCell = false;
    for (var i = 0; i < hotCells.length; i++) {
        if (hotCells[i].row == row && hotCells[i].col == col) {
            hotCells[i].className = classes;
            containsCell = true;
        }
    }

    if (!containsCell) {
        hotCells.push({row: row, col: col, className: classes});
    }

    hot.updateSettings({
        cell: hotCells
    });
}

function removeClass(row, col, mClass) {
    var cell = $("table tr:eq(" + row + ") td:eq(" + col + ")");

    cell.removeClass(mClass);

    var classes = cell.attr("class");

    var hotCells = hot.getSettings().cell;
    for (var i = 0; i < hotCells.length; i++) {
        if (hotCells[i].row == row && hotCells[i].col == col) {
            hotCells[i].className = classes;
        }
    }

    hot.updateSettings({
        cell: hotCells
    });
}

请记住,hot.updateSettings() 是一个缓慢的操作,因此请务必在循环之外进行。