Automatically add css prefix method
How to automatically add prefixes to css styles.
1:step 1
Use the browser's native method to create an element to get style, and get the prefix of the browser according to the created element
let elementStyle = document.createElement('div').style
2:step 2
There are five types of browser prefixes:
Prefix | Browser |
---|---|
webkit | safari, chrome browser |
moz | firefox browser |
The | Opera browser |
ms | ie browser |
No prefix | standard default |
So write a method to determine the prefix of this element?
let screenPrefix = (() => {
const prefix = {
webkit: 'webkitTransform', // safari,chrome等
Moz: 'MozTransform', // firefox
O: 'OTransform', // Opera
ms: 'msTransform', // ie
standard: 'transform' // 默认
}
for (let key in prefix) {
if (elementStyle[prefix[key]] !== undefined) {
return key
}
}
return false
3:step 3
Export a method to accept the css style that you want to add a prefix
export function addPrefix(style) {
if (screenPrefix) {
// 添加前缀返回的方法是false可能是出error了
return false
}
if (screenPrefix === 'transform') {
// 说明不用添加前缀,默认即可
return style
}
// 驼峰命名
return screenPrefix + style.charAt(0).toUpperCase() + style.substr(1)
}
4:step 4
If you need to add a prefix, just call the addPrefix() method in the file that needs to be called.
import {
addPrefix } from 'common/js/dom'
const transform = addPrefix('transform')
The above is all the content shared.
from-------Tyreal