jquery左右拖动表格头部改变td的宽度

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
table{
border-collapse:collapse;
}
</style>
</head>
<body>
<table cellspacing="0" border="1">
<thead>
<tr>
   <th>姓名</th>
   <th>性别</th>
   <th>年龄</th>
   <th>电话</th>
   <th>家庭住址</th>
</tr>
</thead>
<tbody>
<tr>
<td>小明</td>
<td>男</td>
<td>18</td>
<td>15555555555</td>
<td>重庆市沙坪坝区</td>
</tr>
<tr>
<td>小红</td>
<td>女</td>
<td>18</td>
<td>15555555555</td>
<td>重庆市沙坪坝区</td>
</tr>
</tbody>
</table>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function() { 
$("body").append("<div id=\"line\" style=\"width:1px;height:200px;border-left:1px solid #00000000; position:absolute;display:none\" ></div> "); 
});
$("th").bind("mousemove", function(event) { 
var th = $(this); //不给第一列和最后一列添加效果
if (th.prevAll().length <= 1 || th.nextAll().length < 1) { 
return;

var left = th.offset().left; //距离表头边框线左右4像素才触发效果 
if (event.clientX - left < 2 || (th.width() - (event.clientX - left)) < 2) {
th.css({ 'cursor': 'w-resize' }); //修改为你的鼠标图标路径

else {
th.css({ 'cursor': 'default' }); 
}
});
$("th").bind("mousedown", function(event) {
var th = $(this); //与mousemove函数中同样的判断 
if (th.prevAll().length < 1 | th.nextAll().length < 1) {
return; 

var pos = th.offset(); 
if (event.clientX - pos.left < 4 || (th.width() - (event.clientX - pos.left)) < 4) { 
var height = th.parent().parent().height(); 
var top = pos.top;
$("#line").css({ "height": height, "top": top,"left":event .clientX,"display":"" }); //全局变量,代表当前是否处于调整列宽状态
lineMove = true; //总是取前一个TH对象 
if (event.clientX - pos.left < th.width() / 2){ 
currTh = th.prev();
} else {
currTh = th;
}
}
});
$("body").bind("mousemove", function(event) { 
if (lineMove == true) { 
$("#line").css({ "left": event.clientX }).show(); 

});
$("body").bind("mouseup", function(event) {
if (lineMove == true) { 
$("#line").hide(); 
lineMove = false; 
var pos = currTh.offset(); 
var index = currTh.prevAll().length;
currTh.width(event.clientX - pos.left); 
currTh.parent().parent().find("tr").each(function() { 
$(this).children().eq(index).width(event.clientX - pos.left); 
});

}); 
$("th").bind("mouseup", function(event) { 
if (lineMove == true) {
$("#line").hide(); 
lineMove = false; 
var pos = currTh.offset();
var index = currTh.prevAll().length; 
currTh.width(event.clientX - pos.left);
currTh.parent().parent().find("tr").each(function() { 
$(this).children().eq(index).width(event.clientX - pos.left); 
});
}
});
</script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值