Javascript选择表格中的单元格套索样式

Javascript select cells in a table Lasso-style

本文关键字:单元格 套索 样式 选择 表格 Javascript      更新时间:2023-09-26

我是Javascript的新手,我在创建套索样式的表选择工具时遇到了麻烦。

基本上,我希望能够将鼠标拖到表格上,并使该区域的所有单元格高亮显示,以便稍后可以对选定的单元格进行操作。

这是我试图实现的一个非常有缺陷的小提琴。http://jsfiddle.net/kooldave98/ad5Z9/

var element = $("#rectangle");
// on mousedown
$(window).mousedown(function (e1) {
    // first move element on mouse location
    element.show().css({ top: e1.pageY, left: e1.pageX });
    // resize that div so it will be resizing while moouse is still pressed
    var resize = function (e2) {
        // you should check for direction in here and moves with top or left
        element.width(e2.pageX - e1.pageX);
        element.height(e2.pageY - e1.pageY);
    };
    $(window).mousemove(resize);
    // and finally unbind those functions when mouse click is released
    var unbind = function () {
        $(window).unbind(resize);
        $(window).unbind(unbind);
    };
    $(window).mouseup(unbind);
});

我需要能够在表格内的任何方向移动选择工具,然后使用"ctrl"键选择其他单元格。

您可以使用jQuery UI Selectable小部件来做到这一点。

具体来说,一旦您包含了jQuery UI Selectable小部件,您就可以执行

$('table').selectable(
    filter: 'td',      // Ensure elements are selected by table cell
);

然后在你的CSS中,你有.ui-selecting.ui-selected类,你可以设置为你想要的高亮颜色。例如

.ui-selecting {
    background: red;
}
.ui-selected {
    background: blue;
}

你也会有一些你可能不想要的默认选择行为。下面是我如何删除它们的方法:

$(document).ready(function() {
    $('table').mousedown(function(event) {
        return false;
    });
});

虽然希望你有一些更具体的选择,而不仅仅是table。:)