使用 updateDefinition({cssClass: ?}); 更新列定义后制表符网格滚动到左上角

问题描述 投票:0回答:1
我有一个用制表器网格创建的表格。单击该列的一个单元格后,我通过更改其 CSS 样式来“选择”它。在当前的实现中,我观察到的问题是表格“滚动”回左上角。您可以在这里看到简化的示例:

var tabledata = [ {id:1, name:"1111 Bob", age:"12", col:"red", dob:"1"}, {id:2, name:"2222 May", age:"1", col:"blue", dob:"2/05/1982"}, {id:3, name:"3333 Lobowski", age:"42", col:"green", dob:"3/05/1982"}, {id:4, name:"4444 Bob", age:"12", col:"pink", dob:"4"}, {id:5, name:"5555 May", age:"1", col:"black", dob:"5/05/1982"}, {id:6, name:"6666 Lobowski", age:"42", col:"white", dob:"6/05/1982"}, {id:7, name:"7777 Lobowski", age:"42", col:"orange", dob:"7/05/1982"}, {id:8, name:"8888 Bob", age:"12", col:"gray", dob:"8"}, {id:9, name:"9999 May", age:"1", col:"gold", dob:"9/05/1982"}, ]; var table = new Tabulator("#example-table", { data:tabledata, height: "150px", columns:[ //Define Table Columns {title:"Name", field:"name"}, {title:"Favourite Color", field:"col"}, {title:"Date Of Birth", field:"dob"}, ], columnDefaults:{ cellClick:function(e, cell){ if(cell.getElement().classList.contains("column-selected")) { cell.getColumn().updateDefinition({cssClass: ""}); } else { cell.getColumn().updateDefinition({cssClass: "column-selected"}); } }, }, });
.column-selected {
  color:gray;
}
<!DOCTYPE html>
<html lang="en">
<head>
   <link href="https://unpkg.com/[email protected]/dist/css/tabulator.min.css" rel="stylesheet"/>
   <script src="https://unpkg.com/[email protected]/dist/js/tabulator.min.js"></script>
</head>
<body>
<div id="example-table"></div> 

</body>
</html>

为了查看行为,请首先向下滚动到网格底部并选择一个单元格。效果是表格滚动到顶部。 如何避免向后滚动?首先为什么会发生这种情况?

javascript html css tabulator
1个回答
0
投票
The issue you're experiencing where the table scrolls to the top when a cell is selected is likely due to the default behavior of the browser when handling anchor links (e.g., #example-table in the URL). When you click on a cell, the Tabulator library might be updating the URL's hash with the table's ID, causing the page to scroll to that element. To prevent this behavior, you can modify the click event handling in your Tabulator initialization to prevent the default action of the click event. Update the cellClick function as follows: columnDefaults: { cellClick: function (e, cell) { e.preventDefault(); // Prevent the default action if (cell.getElement().classList.contains("column-selected")) { cell.getColumn().updateDefinition({ cssClass: "" }); } else { cell.getColumn().updateDefinition({ cssClass: "column-selected" }); } }, }, By adding e.preventDefault();, you're telling the browser not to perform the default action associated with the event, which, in this case, is scrolling to the top. Make this change in your existing code, and it should prevent the unwanted scrolling behavior when selecting a cell in the table.
    
© www.soinside.com 2019 - 2024. All rights reserved.