常用一些dom元素判断组装方法dom.js
/**是否有class名称*/
export function hasClass(el, className) {
let reg = new RegExp('(^|\\s)' + className + '(\\s|$)')
return reg.test(el.className)
}
/**添加class名称*/
export function addClass(el, className) {
if (hasClass(el, className)) {
return
}
let newClass = el.className.split(' ')
newClass.push(className)
el.className = newClass.join(' ')
}
/**封装前缀*/
let elementStyle = document.createElement('div').style
let vendor = (() => {
let transformNames = {
webkit: 'webkitTransform',
Moz: 'MozTransform',
O: 'OTransform',
ms: 'msTransform',
standard: 'transform'
}
for (let key in transformNames) {
if (elementStyle[transformNames[key]] !== undefined) {
return key
}
}
return false
})()
export function prefixStyle(style) {
if (vendor === false) {
return false
}
if (vendor === 'standard') {
return style
}
return vendor + style.charAt(0).toUpperCase() + style.substr(1)
}
用法:
import {addClass} from 'common/js/dom'
addClass(this.$refs.sliderGroup,'active')/**添加active样式*/
/**
*封装前缀,不然要写多个前缀:webkit,o,ms,moz
* this.$refs.progressBtn.style['transform']=`translate3d(0,${translateY}px,0)`
* this.$refs.progressBtn.style['webkitTransform']=`translate3d(0,${translateY}px,0)`
*/
import {prefixStyle} from 'common/js/dom'
const transform = prefixStyle('transform')
this.$refs.progressBtn.style[transform] = `translate3d(${offsetWidth}px,0,0)`