-
Notifications
You must be signed in to change notification settings - Fork 0
/
createElement.js
71 lines (62 loc) · 2.19 KB
/
createElement.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import isArray from './utils/isArray'
import isString from './utils/isString'
import isSVG from './utils/isSVG'
import setAttributes from './utils/setAttributes'
/**
* 创建 SVG 图标 DOM 元素
* ========================================================================
* @method createElement
* @param {String} name - (必须)当前图标集中的图标名称或者完整的 SVG 图标字符串
* @param {Object} [options] - (可选)配置参数对象
* @param {Number|Array} [options.size] - (可选)图标大小,Number 类型高和宽相等,Array 类型可以单独设置高和宽
* @param {String} [options.color] - (可选)图标颜色
* @param {String} [options.iconSet] - (可选)图标集的名称
* @param {Object} [options.attrs] - (可选)给创建的 icons 元素设置的 HTML 属性对象
* @returns {HTMLElement}
*/
const createElement = (name, options = {}) => {
const ICON = 'ijs-icon'
const size = options.size || 0
const isArraySize = isArray(size)
const color = options.color || ''
const iconSet = options.iconSet || ''
const width = isArraySize ? size[0] : size
const height = isArraySize ? size[1] : size
const defaultRules = size ? `width:${width}px;height:${height}px;` : ''
const cssRules = color ? defaultRules + `color:${color}` : defaultRules
const attrs = options.attrs || {}
const $icon = document.createElement('i')
let binds = ''
let svg = ''
let $svg
if (!isString(name)) {
return null
}
if (isSVG(name)) {
svg = name
} else {
binds =
iconSet && iconSet !== 'icon'
? `xlink:href="#${iconSet}-icon-${name}"`
: `xlink:href="#icon-${name}"`
svg = `<svg><use ${binds}></use></svg>`
}
$icon.innerHTML = svg
if (attrs.className) {
attrs.className = `${ICON} ${attrs.className}`
} else {
attrs.className = `${ICON}`
}
setAttributes($icon, attrs)
$svg = $icon.querySelector('svg')
setAttributes($svg, {
'aria-hidden': true,
xmlns: 'http://www.w3.org/2000/svg',
class: 'ijs-icon__svg',
width: 200,
height: 200,
style: cssRules
})
return $icon
}
export default createElement