This article mainly introduces JS to implement a fixed table header and the header can scroll with horizontal scrolling. Friends in need can refer to it. I hope it can help everyone.
Let’s look at a rendering first
Ideas:
1. Use a table for the head and a Wrapped with p, the specific content of the table is used as a table
2. The p outside the head is positioned relatively using positon: relative
3. Get the height of the entire table
4 , Get the distance between the dom of the table (or the dom that wraps the table) and the top of the page offsetTop
5. The distance between the zero point of scrolling and the height of the table + the distance between the table and the top of the page. If the scroll exceeds this, let Return the top value of the head to 0 or leave it unchanged
## Of course there are many areas that can be optimized, I just show a small idea hehehe Off topic Why use a red table header because it is conspicuous? HahahaJS code
/** * 最重要的一点是头和身体是两个table 然后定位用relative 然后通过滚动来计算 * */ function FixedHead (){ if( !(this instanceof FixedHead) ){ return new FixedHead() }; this.$dom = $('.dataTables_scrollHead'); // 表头外层dom this.offsetTop = this.$dom.offset().top; // 表头外层dom距离顶部的高度 this.parents = this.$dom.parents('.dataTables_scroll'); // 表头外层dom最外面的盒子(包裹着table的盒子) this.outBoxHeight = this.parents.height(); // 表头外层dom最外面的盒子(包裹着table的盒子)的高度 this.maxHeight = this.offsetTop + this.outBoxHeight; // 滚动的零界点 最多能滚动到哪里 this.scroll(); } FixedHead.prototype = { constructor: FixedHead, scroll: function(){ var that = this; $(window).scroll(function(){ var scrollTop = $(this).scrollTop(); if((scrollTop > that.offsetTop) && (scrollTop < that.maxHeight)){ that.$dom.css('top', (scrollTop - that.offsetTop + 50)+'px') // 这个50是因为我的头部导航固定在顶部 高是50 所以要加上 }else { var topCss = that.$dom.css('top'); if(topCss === '0px' || topCss === 'auto'){ }else { that.$dom.css('top', '0px') } } }) } }
How to operate various table tables with jquery Summary of method examples
#5 ways to achieve the slash header effect in table tables in html5
Content level of table tables in html and vertically centered display example code
The above is the detailed content of Detailed explanation of JS implementation of fixed table header and horizontal scrolling of the table header. For more information, please follow other related articles on the PHP Chinese website!