jQuery tablesorter 2.0:表头含子表格时stickyHeaders滚动失效求助
I’ve run into this exact issue before—when your table header cells contain nested tables, the default stickyHeaders behavior only copies over text content, not the full DOM structure, leading to those subtable elements disappearing once scrolling activates. Here’s how to fix it:
Root Cause
The stickyHeaders widget by default extracts just the text from each header cell to populate the sticky clone. It doesn’t account for complex child elements like nested tables, so those get left out entirely when the sticky header activates.
Solution: Customize Header Content Copying
We can override the widget’s header content copying logic using the stickyHeaders_copyHeaderContent callback. This lets us manually clone the full DOM structure of each header cell, including any nested tables and their styling/events.
Step 1: Update Tablesorter Initialization
Modify your tablesorter setup to include the custom callback in the widget options:
$(function() { $('table').tablesorter({ widgets: ['stickyHeaders'], widgetOptions: { // Override default content copying behavior stickyHeaders_copyHeaderContent: function($originalCell, $stickyCell) { // Clear existing content in the sticky cell $stickyCell.empty(); // Deep clone all contents of the original header cell (includes events) $stickyCell.append($originalCell.contents().clone(true, true)); // Copy over CSS classes to match the original header's styling $stickyCell.attr('class', $originalCell.attr('class') || ''); } } }); });
Step 2: Adjust CSS for Nested Tables
You might need to tweak your CSS to ensure the nested table displays correctly in the sticky header without clipping or layout issues:
/* Ensure sticky header cells can contain nested tables without clipping */ .tablesorter-sticky-header th { position: relative; overflow: visible; padding: 0.5rem; /* Match your original header padding */ } /* Style the nested table to fit perfectly within the sticky header cell */ .tablesorter-sticky-header th > table { width: 100%; margin: 0; border-collapse: collapse; }
Key Notes
- The
clone(true, true)method performs a deep clone, which copies both the DOM structure and any attached event handlers to the nested table. This ensures any interactivity in the subtable works in the sticky header too. - If your nested tables load dynamic content after the initial tablesorter setup, re-trigger the sticky header initialization with
$('table').trigger('stickyHeaders_initialize')once the content is ready.
内容的提问来源于stack exchange,提问作者TeeOhDeeDee

