使用jquery实现鼠标按下选中表格中的多个单元格进行数据求和

一、需求

最终的效果需要达到像在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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值