一、需求
最终的效果需要达到像在excel中选中一列的某些数据后,在这列最下方显示求和结果:如下图:
二、实现
先贴上完整的代码:
$("tbody td").mousedown(function () {
//每次先清除一下上次选中的单元格的背景色
$("tbody td").css('background-color', '');
$("tbody td").mousemove(onMousemove);
$("tbody td").mouseup(onMouseup);
});
function onMousemove() {
$(this).css('background-color', '#aaa');
}
var cellVal = parseFloat(0,10);
var cellIndex = 0;
var re = /(^[\-0-9][0-9]*(.[0-9]+)?)$/; //判断字符串是否为数字
function onMouseup() {
$("tbody").find("td").each(function () {
if($(this).attr('style')=="background-color: rgb(170, 170, 170);"){
var nubmer = $(this).context.innerText;
if (!re.test(nubmer)) {
nubmer = 0;
}
cellVal += parseFloat(nubmer,10);//cellIndex
cellIndex = $(this).context.cellIndex;//选中数据所在第几列
}
});
var html = "";
for(var i=0;i<cellIndex;i++){
html+="<td></td>"
}
html+="<td>"+cellVal.toFixed(2)+"</td>";
//共有多少列
var totalTh = $("table th").size();
for(var i=0;i<totalTh - (cellIndex+1);i++){
html+="<td></td>"
}
$("tfoot").html(html);
cellVal = 0;
cellIndex = 0;
$("tbody td").unbind('mousemove', onMousemove);
}
三、总结
1、利用mousedown、mousemove、mouseup实现选中表格单元格的效果
mousedown:按下鼠标的时候会触发这个事件;触发这个事件的时候会赋予列mousemove和mouseup事件
mousemove:鼠标只要移动就会触发这个事件;触发这个事件的时候将该单元格填充上背景色,实现选中效果
mouseup:鼠标释放的时候就会触发这个事件;触发这个事件的时候会解除mousemove事件,不然只要鼠标移动就会将扫过的单元格填充上颜色
2、求和
最终的效果是,放开鼠标就会在该列下面计算出结果,所以我将求和操作放在mouseup事件里面
主要思路:
遍历表格的单元格,有选中背景色的话,就通过innerText获取到单元格的数据,进行累加
至于结果数据位于哪一列就用cellIndex
3、js中两个小数相加减的时候会出现小数位多出好多位的问题,所以使用了toFixed(2)来保留小数位后2位
4、选中单元格的时候,会选中页面多余的内容,
添加如下样式:
table tr td{
-webkit-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
user-select:none;
}