jQuery实现拖动调整表格单元格大小的代码实例教程
jquery实现的拖动调整表格td单元格的大小:
在实际应用中,可能有这样的需求,那就是需要调整td单元格的大小。
也许是为了便于观察,也许是其他原因,反正这样的需求是有的,下面就分享一段能够实现此功能的代码。
代码实例如下:
代码如下:
<!doctype html>
<html>
<head>
<meta charset=" utf-8">
<title>博客园</title>
<style type="text/css" >
table {
border-collapse: collapse;
}
td {
text-align: center;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
(function ($){
$.fn.tableresize = function () {
var _document = $("body");
$(this).each(function () {
if (!$.tableresize) {
$.tableresize = {};
}
var _table = $(this);
//设定id
var id = _table.attr("id") || "tableresize_" + (math.random() * 100000).tofixed(0).tostring();
var tr = _table.find("tr").first(), ths = tr.children(), _firstth = ths.first();
//设定临时变量存放对象
var cobjs = $.tableresize[id] = {};
cobjs._currentobj = null, cobjs._currentleft = null;
ths.mousemove(function (e) {
var _this = $(this);
var left = _this.offset().left,
top = _this.offset().top,
width = _this.width(),
height = _this.height(),
right = left + width,
bottom = top + height,
clientx = e.clientx,
clienty = e.clienty;
var leftside = !_firstth.is(_this) && math.abs(left - clientx) <= 5,
rightside = math.abs(right - clientx) <= 5;
if (cobjs._currentleft||clienty>top&&clienty<bottom&&(leftside||rightside)){
_document.css("cursor", "e-resize");
if (!cobjs._currentleft) {
if (leftside) {
cobjs._currentobj = _this.prev();
}
else {
cobjs._currentobj = _this;
}
}
}
else {
cobjs._currentobj = null;
}
});
ths.mouut(function (e) {
if (!cobjs._currentleft) {
cobjs._currentobj = null;
_document.css("cursor", "auto");
}
});
_document.mousedown(function (e) {
if (cobjs._currentobj) {
cobjs._currentleft = e.clientx;
}
else {
cobjs._currentleft = null;
}
});
_document.mouseup(function (e) {
if (cobjs._currentleft) {
cobjs._currentobj.width(cobjs._currentobj.width() + (e.clientx - cobjs._currentleft));
}
cobjs._currentobj = null;
cobjs._currentleft = null;
_document.css("cursor", "auto");
});
});
};
})(jquery);
$(document).ready(function () {
$("table").tableresize();
});
</script>
</head>
<body>
<table cellspacing="0" border="1" rules="all">
<tbody>
<tr>
<td style="width:200px;">id</td>
<td style="width:200px;">名字</td>
<td style="width:200px;">年纪</td>
<td style="width:200px;">地址</td>
<td style="width:200px;">电话</td>
</tr>
<tr>
<td>22</td>
<td>name:44</td>
<td>age:23</td>
<td>address:47</td>
<td>phone:15</td>
</tr>
<tr>
<td>28</td>
<td>name:42</td>
<td>age:68</td>
<td>address:30</td>
<td>phone:50</td>
</tr>
<tr>
<td>29</td>
<td>name:63</td>
<td>age:48</td>
<td>address:90</td>
<td>phone:76</td>
</tr>
</tbody>
</table>
</body>
</html>