本文实例为大家分享了Jquery实现拖拽table表头改变列宽的具体代码,供大家参考,具体内容如下 效果: 直接上代码,有注释: <!DOCTYPE html> <
本文实例为大家分享了Jquery实现拖拽table表头改变列宽的具体代码,供大家参考,具体内容如下
效果:
直接上代码,有注释:
<!DOCTYPE html>
<html>
<head>
<style>
table, td, th {
border: 1px solid #DDD;
text-align: left;
}
table {
border-collapse: collapse;
width: 100%;
table-layout: fixed;
}
th, td {
padding: 5px;
position: relative;
user-select: none;
Word-break: break-all;
}
.th-sisehandler {
position: absolute;
right: -0.5px;
top: 0;
z-index: 1;
width: 5px;
height: 100%;
padding-left: 4px;
cursor: col-resize;
}
.th-sisehandler::after {
content: '';
display: block;
width: 10px;
background-color: #4CAF50;
height: 100%;
}
.siselayer {
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
z-index: 9999;
background-color: #4445a049;
cursor: col-resize;
}
</style>
<meta charset="UTF-8">
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div style="width: 600px;overflow: auto">
<table>
<tr>
<th width="150">Firstname</th>
<th width="150">Lastname</th>
<th width="150">Savings</th>
</tr>
<tr>
<td>Bill</td>
<td>Gates</td>
<td>$100</td>
</tr>
<tr>
<td>Steve</td>
<td>Jobs</td>
<td>$150</td>
</tr>
<tr>
<td>Elon</td>
<td>Musk</td>
<td>$300</td>
</tr>
<tr>
<td>Mark</td>
<td>Zuckerberg</td>
<td>$250</td>
</tr>
</table>
</div>
<script>
$("th").mouseover(function (e) {
if (($(this).find("div").length <= 0)) {
//1.鼠标移动到表头上时,在th内部添加一个div 元素,用于处理后续拖动事件
$(this).append("<div class='th-sisehandler'></div>")
//2.处理上面添加的元素的鼠标按下事件
$(".th-sisehandler").mousedown(function (evt) {
//3.在添加的元素上按下时,记录下当前的th表头
let dragTh = $(this).parent()
//4.记录按下时的鼠标位置
let oldClientX = evt.clientX;
//5.获取当前鼠标按下时的表头的宽度
let oldWidth = dragTh.width();
let changeSizeLayer = $('<div class="siselayer"></div>');
$("body").append(changeSizeLayer);
changeSizeLayer.on('mousemove', function (evt) {
//7.处理遮罩层的鼠标移动事件,计算新的表头宽度
var newWidth =evt.clientX - oldClientX + oldWidth;
//设置新的宽度
dragTh.attr('width',Math.max(newWidth,1));
});
changeSizeLayer.on('mouseup', function (evt) {
//8.鼠标按键复位时,要清楚遮罩层
changeSizeLayer.remove();
dragTh.find('.th-sisehandler').remove();
});
})
}
$(this).mouseleave(function () {
//9.鼠标离开表头时,要移除第一步添加的div
$(this).find("div").remove()
})
})
</script>
</body>
</html>
--结束END--
本文标题: jquery实现拖拽table表头改变列宽
本文链接: https://www.lsjlt.com/news/140062.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0