甘特图实例 dhtmlxGantt.js
本文介绍了如何使用dhtmlxGantt库创建一个基础的甘特图示例,并对其进行汉化和自定义配置。首先,通过引入dhtmlxgantt.css和dhtmlxgantt.js文件初始化甘特图。接着,通过设置gantt.i18n.setLocale("cn")实现核心文本的汉化,并配置了时间轴、按钮等元素的显示格式。为了限制用户操作,禁用了任务拖动、双击编辑等功能,并将甘特图设置为只读模式。此外,隐藏了工具栏、快速操作栏和表头操作栏,确保用户仅能查看而无法修改数据。最后,通过gantt.parse方法加载示例数据,并调用gantt.render()渲染甘特图。该示例展示了如何通过灵活的配置实现甘特图的定制化需求。
效果图:
<!DOCTYPE html>
<html><head><title>dhtmlxGantt 基础示例</title><link href="dhtmlxgantt.css" rel="stylesheet"><script src="dhtmlxgantt.js"></script><style>body {margin: 0;font-family: Arial;}.gantt-container {width: 100%;height: 100vh;}/* 隐藏所有加号按钮 */.gantt_add {display: none !important;}/* 或仅隐藏左侧任务树的加号按钮 */.gantt_tree_icon.gantt_add {display: none !important;}.gantt_last_cell {display: none !important;}</style>
</head><body><div id="gantt" class="gantt-container"></div><script>//汉化//文件内容示例gantt.i18n.setLocale("cn");// 核心文本汉化gantt.config.labels = {new_task: "新建任务",icon_save: "保存",icon_cancel: "取消",icon_details: "详情",icon_edit: "编辑",icon_delete: "删除",confirm_closing: "更改将丢失,确定关闭?",confirm_deleting: "任务将永久删除,确定继续?",section_description: "描述",section_time: "时间范围"};// 时间轴汉化gantt.config.month_date = "%Y年%m月";gantt.config.day_date = "%m月%d日";gantt.config.week_date = "第%W周";gantt.config.scale_date = "%Y年%m月%d日";gantt.config.buttons_left = [{ text: "周视图", command: "scale_cells", param: "week" },{ text: "月视图", command: "scale_cells", param: "month" }];gantt.config.buttons_right = [{ text: "导出PDF", command: "export_pdf" }];// 完全禁用任务拖动// 1. 初始化配置gantt.config.date_format = "%Y-%m-%d";// // 完全禁用任务拖动// gantt.config.drag_move = false;// gantt.config.drag_resize = false;gantt.config.select_task = false;// 禁用所有交互事件(包括双击编辑)gantt.config.interaction = {click: false,//禁用单击dblclick: false,//禁用双击drag: false,// 禁用任务拖动resize: false 禁用调整大小};// 仅允许查看但禁止修改gantt.config.readonly = true;// 禁用任务点击选中// gantt.config.scale_unit = "week";gantt.config.subscales = [{ unit: "day", step: 1, date: "%D" }];// 初始化时禁用任务创建按钮gantt.config.show_add_button = false;gantt.config.toolbar = []; // 清空工具栏gantt.config.show_quick_info = false; // 隐藏快速操作栏gantt.config.show_grid_header = false; // 隐藏表头操作栏// 2. 加载数据gantt.init("gantt");gantt.parse({data: [{ id: 1, text: "项目启动", start_date: "2025-05-01", duration: 7, progress: 0.5 },{ id: 2, text: "需求分析", start_date: "2025-05-08", duration: 5, parent: 1 },{ id: 3, text: "UI设计", start_date: "2025-05-10", duration: 8, parent: 1 },{ id: 4, text: "开发", start_date: "2025-05-15", duration: 10 },{ id: 5, text: "测试", start_date: "2025-05-16", end_date: "2025-05-20" }],// links: [// { id: 1, source: 2, target: 3, type: "0" } // 0表示"完成-开始"依赖关系// ]});// 或通过事件拦截(更灵活)gantt.attachEvent("onBeforeTaskDrag", function () {return false; // 取消拖动操作});// 刷新视图使配置生效gantt.render();</script>
</body></html>
实例资源包下载:https://download.csdn.net/download/lybwwp/90892502