我想在 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/