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

In Javascript: I need to implement selection via click, control click and shift clickon rows in an ht

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!

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!

Share Improve this question asked Feb 28, 2010 at 20:59 sdforsdfor 6,47816 gold badges53 silver badges62 bronze badges 1
  • 1 Selection of what? Can you be more specific in your requirements? – ntownsend Commented Feb 28, 2010 at 22:01
Add a ment  | 

1 Answer 1

Reset to default 5

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745589423a4634742.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信