class freezingTable { constructor(containId, freeClass, headSelect, freeType) {//constructor是一个构造方法,用来接收参数 this.tdLefts = []; this.tdWidths = []; this.freeLeft = document.getElementById(containId).offsetLeft; this.$free = $("#" + containId); this.$frist = this.$free.find("." + freeClass); headSelect = headSelect || "table thead td"; this.$head = $(headSelect); //this.freeType = freeType || 1; this.freeClass = freeClass; } freezing() { var _this = this; var _$free = _this.$free; _this.freezingHead();//固定头部 var scroLeft = _$free.scrollLeft(); //向左滚动的距离 _this.$frist.each(function (index, first) { if (!_this.tdLefts[index]) { if (index > 0) { _this.tdLefts[index] = first.offsetLeft - _this.tdWidths[index - 1]; _this.tdWidths[index] = _this.tdWidths[index - 1] + first.offsetWidth; } else { _this.tdLefts[index] = first.offsetLeft; _this.tdWidths[index] = first.offsetWidth; } } _this.moveAllFreezing(first, _this.tdLefts[index], scroLeft); }); } //table表头固定 freezingHead() { var _this = this; var $free = _this.$free; var $head = _this.$head; var scroTop = $free.scrollTop(); //向下滚动的距离 var starTop = 0; //开始滚动距离 var scroDis = scroTop;//滚动距离 if (scroDis > starTop) $head.css("top", scroDis); else $head.css("top", 0); var thHeight = $head.height(); var step = thHeight / 5;//分5次过渡,每step像素过渡一次 var tol = Math.ceil(scroDis / step); if (scroTop == 0) { $head.removeClass("isScrolling").css("opacity", 1); } else if (scroDis > 0 && scroDis < thHeight) { $head.addClass("isScrolling").css("opacity", 0.2 * tol); if ($head.hasClass("")) { } } else { $head.addClass("isScrolling").css("opacity", 1); } } //只需在标题添加first就可以固定一列 moveAllFreezing(first, firstLeft, scroLeft) { var _this = this; var $free = _this.$free; var freeLeft = _this.freeLeft; var $first = $(first); var index = $first.index() + 1; var $columns = $free.find(`thead th.${_this.freeClass}:nth-child(${index}),tbody .payment:nth-child(${index})`); var starLeft = firstLeft - freeLeft + 5; //开始滚动距离 var scroDis = scroLeft - starLeft;//滚动距离 if (scroDis > 0) { $columns.css("left", scroDis); } else { $columns.css("left", 0); } var thWidth = $first.width(); var step = thWidth / 5;//分5次过渡,每step像素过渡一次 var tol = Math.ceil(scroDis / step); if (scroDis <= 0) { $columns.removeClass("isScrolling").css("opacity", 1); } else if (scroDis > 0 && scroDis < thWidth) { $columns.addClass("isScrolling").css("opacity", 0.2 * tol); } else { $columns.addClass("isScrolling").css("opacity", 1); } } }