Table 使用position:sticky实现固定标题和尾列
工作中,经常需要展示很多列的table, 难免遇到表格变形的问题, 此文提供了一种解决方案效果如上上代码!DOCTYPE html html langzh head meta charsetUTF-8 meta nameviewport contentwidthdevice-width, initial-scale1.0 title使用position:sticky实现固定标题和尾列,可左右拖动的table/title !-- 插入Vue -- script srchttps://cdn.jsdelivr.net/npm/vue/dist/vue.js/script script srchttp://code.jquery.com/jquery-2.1.1.min.js/script style .main{ width: 800px; overflow:auto; height:400px; /* 设置固定高度 */ } td, th { /* 设置td,th宽度高度 */ border:1px solid #d7d7d7; width:100px; height:30px; text-align: center; } th { background-color:lightblue; box-shadow:0px 2px 3px #d9d9d9 } table { table-layout: fixed; width: 200px; /* 固定宽度 */ } td:last-child, th:last-child { position:sticky; right:0; /* 尾行永远固定在右侧 */ z-index:1; background-color:lightpink; box-shadow:-2px 0px 2px #d9d9d9 } thead tr th { position:sticky; top:0; /* 列首永远固定在头部 */ } th:last-child{ z-index:2; background-color:lightpink; } /* 禁止选中 */ .no_copy{ moz-user-select: -moz-none; -moz-user-select: none; -o-user-select:none; -khtml-user-select:none; -webkit-user-select:none; -ms-user-select:none; user-select:none; } /style /head body div idapp div classmain table cellspacing0 thead tr th标题1/th th标题2 /th th标题3 /th th标题4 /th th标题5 /th th标题6 /th th标题7 /th th标题 /th th操作 /th /tr /thead tbody tr v-for(item, index) in 30 :keyindex td {{index}}/td td /td td /td td /td td /td td /td td /td td /td td编辑/td /tr /tbody /table /div /div /body script var app new Vue({ el: #app }) //可鼠标左键按住左右拖动效果实现 let dragMoveX (container) { var flag; var downX; var scrollLeft; //鼠标按下 $(document.body).on(mousedown, container, function (event) { flag true; downX event.clientX; scrollLeft $(this).scrollLeft(); }); //鼠标移动 $(container).on(mousemove, function (event) { if (flag) { $(this).addClass(no_copy); //拖动时禁止触发选中 var moveX event.clientX; var scrollX moveX - downX; if (scrollX 0 scrollLeft 0) { $(this).scrollLeft(scrollLeft - scrollX) } else { $(this).scrollLeft(scrollLeft - scrollX) } } }); //鼠标释放 $(container).on(mouseup, function () { $(this).removeClass(no_copy); //取消禁止选中 flag false; }); //鼠标移出元素 $(container).on(mouseleave, function (event) { flag false; if (event.pageX 0 || event.pageX document.body.offsetWidth) { flag false; } }); } dragMoveX(.main); /script /html简单修改下就能运用在实际项目中了