JavaScript 单元格选择

标签 javascript selection cell

我想在 HTML 表格中选择一个单元格范围,并使用 Javascript 更改所选单元格的背景颜色。是否有一个事件可以获取所选单元格的所有 id?

<小时/>

我尝试了这段代码:

function getSelectedCells()
{
   selObj = window.getSelection();
   alert(selObj);
}

它打印出所选单元格的单元格内容。有谁知道我如何使用它来获取所选单元格的ID?

最佳答案

我会尝试你的方法。我自己找到了一个解决方案,但它远非漂亮,只是因为我知道单元格的 id 是如何构造的。这是代码,但它仅有时有效。我猜正则表达式有点问题。我用它来避免更改错误单元格的背景:

function foo() 
{  
    selecIds = new Array();

    sel = window.getSelection();

    firstPosSelA = sel.anchorNode;
    lastPosSelF = sel.focusNode;

    firstCellId = firstPosSelA.parentNode.getAttribute("id");
    lastCellId = lastPosSelF.parentNode.getAttribute("id");

    startSelNumInd = firstCellId.indexOf("wc");
    endSelNumInd = lastCellId.indexOf("wc");

    startSelNum = firstCellId.substring(startSelNumInd + 2);
    endSelNum = lastCellId.substring(endSelNumInd + 2);
    firstSelecRow = firstCellId.substring(0, startSelNumInd + 2);

    for ( i = startSelNum; i <= endSelNum; i++)
    {
        cellid = firstSelecRow + i;
        selecIds.push(cellid); 
    }

    alert(selecIds);

    for ( eachSelCell in selecIds)
    {
        currentElement = document.getElementById(selecIds[eachSelCell]);
        backColor = currentElement.style.backgroundColor;

        if (backColor !='' || backColor!='#C0C0C0' || backColor!='#c0c0c0' || backColor!='rgb(192, 192, 192)' || backColor!='RGB(192, 192, 192)')
        {
            if (/\d\w/.test(selecIds[eachSelCell]) || (/fc/.test(selecIds[eachSelCell])))
            {
            }   
            else
            {
                changeBackgroundColor(selecIds[eachSelCell]);
            }   
        }
    }
}

关于JavaScript 单元格选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3157366/

相关文章:

javascript - 你可以吗?如果可以,你如何获得默认光标作为图像?

wpf - ListViewItem 未选择按钮单击

javascript - 突出显示 html 表格单元格 onclick 并使用 CTRL + C 复制值

javascript - 遇到从文档中丢失 jQuery 焦点 "onkeypress"的问题

javascript - 如何将中间件绑定(bind)到 socket.io 中的事件

javascript - 选中时用线为文本下划线

vim - 如何在 Vim 中实现类似 MATLAB 的单元格模式

iphone - 如何在 iphone 的表格单元格内显示多行文本?

javascript - 防止滚动事件

ASP.NET DropDownList 在回发时不保留所选项目