开发者

javascript: Implementing selection via click, control click and shift click, such as in windows explorer

开发者 https://www.devze.com 2022-12-21 23:42 出处:网络
In Javascript: I need to implement selection via click, control click and shift clickon rows in an html table, such as in windows explorer, and I hate to write 开发者_如何学编程it if the code alread

In Javascript:

I need to implement selection via click, control click and shift click on rows in an html table, such as in windows explorer, and I hate to write 开发者_如何学编程it if the code already exists.

Can anyone point me in the right direction?

thanks!


The required script is very simple. Something like this will work:

var keyDown = null;
var selectedRows;
var allRows;

function bindEvents() {
    allRows = document.getElementsByTagName("tr");
    document.onkeydown = function(e) {
        if (!e) e = window.event;
        if (e.ctrlKey) keyDown = "ctrl";
        if (e.shiftKey) keyDown = "shift";
    };

    document.onkeyup = function(e) {
        keyDown = null;
    };

    for (var i = 0, l = allRows.length; i < l; i++) {
        allRows[i].onclick = new Function("selectRow(" + i + ")");
    }
}

function selectRow(rowID) {
    if (!keyDown)
        selectedRows = [rowID];
    else {
        if (keyDown == "ctrl")
            selectedRows.push(rowID);
        else {
            if (selectedRows.length > 0) {
                var lastSelected = selectedRows[selectedRows.length - 1];
                for (var i = lastSelected + 1; i <= rowID; i++)
                    selectedRows.push(i);
            } else
                selectedRows.push(rowID);
        }
    }

    for (var i = 0, l = allRows.length; i < l; i++)
        allRows[i].style.backgroundColor = "";

    if (selectedRows.length > 0)
        for (var i = 0, l = selectedRows.length; i < l; i++)
            allRows[selectedRows[i]].style.backgroundColor = "red";

    keyDown = null;
}

Add body onload="bindEvents()" and it will work on all tables you have in the page (if you have more than one, you might have to change the script to only use the one you care about). It's not the most beautiful code, but it will do the trick.

0

精彩评论

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

关注公众号