本文介紹了如何使用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