文末有小测试哦!
通过 mxConstant
的两种方式:
以 STYLE_
开头的样式属性
有如下的几种方式:
// 便于书写,本文以下出现的graph均为mxGraph的实例
// 先 GET 获取vertex默认属性,然后修改之
const style = graph.getStylesheet().getDefaultVertexStyle();
style[mxConstants.STYLE_FONTSIZE] = '14';
----------
// 或者 先设置属性,然后 PUT 到vertex的默认属性中
const style = {};
style[mxConstants.STYLE_FONTSIZE] = '14';
graph.getStylesheet().putDefaultVertexStyle(style);
----------
// 也可以使用 putCellStyle()方法,设置一个自定义的样式变量'customStyle',
// 然后'customStyle'就可以在inserVertex、inserEdge时使用
const style = {};
style[mxConstants.STYLE_FONTSIZE] = '14';
style[mxConstants.STYLE_FONTCOLOR] = 'rgba(100, 100, 100, 1)';
graph.getStylesheet().putCellStyle('customStyle', style);
不是以 STYLE_
开头的样式属性,
直接赋值就行:
mxConstants.LINE_HEIGHT = 1.8;
mxConstants.DEFAULT_IMAGESIZE = 66;
通过 insertVertex()
的方式
采用"key1 = value1; key2 = value2; ..."
的形式,设置insertVertex(parent, id, value, x, y, width, height, style)
方法中的style
参数,其实这个方法本质和上面设置mxConstants
类似。相应的key
,value
也不是随便写的,对应的属性也是需要在mxConstants
的文档中能查找到:
// 这里只介绍`insertVertex`方法的`style`参数
let cell = graph.insertVertex(
parent,
id,
value,
x,
y,
width,
height,
// 这里的驼峰式书写,看上去和正常的css一模一样,容易让人误以为所有的css属性只要采用驼峰式都可以生效,但是 并非如此。
// 因为这里的属性其实也是和mxConstans中一一对应的,所有只有官方文档中有定义的属性,才能生效。
'fontColor=rgba(100, 100, 100, 1);fontSize=14;'
)
更多的可设置属性
文档自查方式
- 以上的方法,必须按照官方文档中的key、value规范进行设置,否则样式设置无效。
查看mxConstant
的官方文档页面:
https://jgraph.github.io/mxgraph/docs/js-api/files/util/mxConstants-js.html - 具体如何查看呢?以下我摘抄一段文档中的属性,大家就明白了:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VmbOYcWP-1659630134362)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/fa28338b20e640bdb4cfdc9cd9effc6f~tplv-k3u1fbpfcp-watermark.image?)]
Value is ““fontSize”: 注意这里的value就是指的insertVertex方法的style中的key值'fontSize=14;'
小测试
- 请问你能看出以下的设置方法里,哪些是错误的呢?错误原因是什么呢?
欢迎小伙伴在评论区发表你的解答或者疑问! - 题目一
style[mxConstants['position'] = 'absolute';
- 题目二
style[mxConstants.LINE_HEIGHT] = 1;
- 题目三
let cell = graph.insertVertex( parent, id, value, x, y, width, height, 'wordBreak=break-all;' );