GOJS Palette组件对齐异常问题求助
GoJS Palette 元素对齐异常(无法居中)问题解决
问题根源分析
你的代码里有几个关键错误导致元素无法居中且布局异常:
- 两个手动添加的
Part都设置了position: new go.Point(0, 0),导致它们完全重叠,视觉上只能看到一个元素。 - 图片的
alignment用了new go.Spot(0, 0.5),这个参数的X值为0代表左对齐,不是居中。 - Palette没有配置合适的布局管理器,手动添加的元素无法被正确排列。
修正后的代码
// 初始化Palette时配置横向流式布局,自动排列元素 const Toolbar = new go.Palette("ToolbarDiv", { nodeTemplateMap: Diagram.nodeTemplateMap, model: new go.GraphLinksModel([ {text: "Rectangle"}, {category: "RoundedRectangle", text: "RoundedRectangle"} ]), layout: new go.HorizontalFlowLayout({ spacing: 15, // 元素间的间距 alignment: go.Spot.Center // 布局内元素整体居中 }) }); // 添加保存按钮组件 Toolbar.add( $(go.Part, "Table", { selectable: false }, // 移除固定position,让布局管理器控制位置 $(go.TextBlock, "", { row: 0, font: "700 8px Droid Serif, sans-serif" }), $(go.Panel, "Horizontal", { click: (e, node) => save(), alignment: go.Spot.Center // 让按钮容器在Table面板中居中 }, $(go.Panel, "Auto", $(go.Picture, { width: 60, height: 60, source: "save.png", alignment: go.Spot.Center // 图片在容器内居中 }) ) ) ) ); // 添加加载按钮组件 Toolbar.add( $(go.Part, "Table", { selectable: false }, $(go.TextBlock, "", { row: 0, font: "700 8px Droid Serif, sans-serif" }), $(go.Panel, "Horizontal", { click: (e, node) => save(), alignment: go.Spot.Center }, $(go.Panel, "Auto", $(go.Picture, { width: 60, height: 60, source: "load.png", alignment: go.Spot.Center }) ) ) ) );
额外优化建议
- 如果需要让Palette容器本身在页面中居中,可配合CSS设置:
#ToolbarDiv { margin: 0 auto; width: fit-content; } - 不要随意给
Part设置固定position,除非是绝对定位的特殊需求,交给GoJS的布局管理器处理能避免大部分布局异常。 - 如果后续给TextBlock添加内容,可设置
wrap: go.TextBlock.WrapFit让文本自适应换行,保证布局稳定。
内容的提问来源于stack exchange,提问作者TaeHee Jang
相关产品推荐
相关产品推荐

