如何在点击事件中修改Syncfusion EJ2 Tree-grid列头的字体大小、颜色及背景色
Syncfusion EJ2 TreeGrid 点击修改列头样式实现方案
Syncfusion EJ2 TreeGrid 原生提供了headerCellClick列头点击事件,不需要手动绑定DOM事件,直接配置该事件即可实现需求,具体实现逻辑如下:
核心实现步骤
- 给TreeGrid组件配置
headerCellClick事件监听,事件触发时会自动返回当前点击的列头DOM元素、对应列的配置信息等参数 - 在事件回调中操作列头DOM元素,直接修改内联样式,或者添加自定义CSS类实现样式修改,后者更适合批量样式管理
代码示例
纯JS版本
let treeGridObj = new TreeGrid({ dataSource: sampleData, treeColumnIndex: 1, columns: [ { field: 'taskID', headerText: '任务ID', width: 90 }, { field: 'taskName', headerText: '任务名称', width: 180 }, { field: 'duration', headerText: '时长', width: 80 } ], // 绑定列头点击事件 headerCellClick: function(args) { // args.element 就是当前点击的列头DOM元素 const headerCell = args.element; // 直接修改内联样式,可按需调整参数 headerCell.style.fontSize = '18px'; headerCell.style.color = '#ffffff'; headerCell.style.backgroundColor = '#2385bb'; // 如需仅保留一个高亮列头,先清空所有列头样式再修改当前即可 // document.querySelectorAll('.e-headercell').forEach(cell => { // cell.style.fontSize = ''; // cell.style.color = ''; // cell.style.backgroundColor = ''; // }) } }); treeGridObj.appendTo('#TreeGrid');
Vue框架版本
<template> <ejs-treegrid :dataSource="data" :treeColumnIndex="1" @headerCellClick="onHeaderClick"> <e-columns> <e-column field='taskID' headerText='任务ID' width='90'/> <e-column field='taskName' headerText='任务名称' width='180'/> <e-column field='duration' headerText='时长' width='80'/> </e-columns> </ejs-treegrid> </template> <script> export default { methods: { onHeaderClick(args) { const headerCell = args.element; // 样式修改逻辑和纯JS版本完全一致 headerCell.style.fontSize = '18px'; headerCell.style.color = '#fff'; headerCell.style.backgroundColor = '#2385bb'; } } } </script> <!-- 自定义类方案(推荐)的样式示例 --> <style> .custom-header-active { font-size: 18px !important; color: #ffffff !important; background-color: #2385bb !important; } </style>
注意事项
- 若使用自定义CSS类方案,需注意样式优先级,必要时加
!important覆盖EJ2原生列头样式 - 该方案基于官方原生事件实现,不会影响列头自带的排序、过滤等交互功能的正常使用
内容的提问来源于stack exchange,提问作者Vishnu Mevada
相关产品推荐
相关产品推荐

