js修改css時如何考慮兼容性問題es5+es6
阿新 • • 發佈:2017-08-13
return defined 使用方法 get 修改 export mstr end 寫法
es5的寫法
var elementStyle = document.createElement(‘div‘).style var vendor = (function(){ 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 })() function prefixStyle(style) { if (vendor === false) { return false } if (vendor === ‘standard‘) { return style } return vendor + style.charAt(0).toUpperCase() + style.substr(1) }
使用方法
1 <!DOCTYPE html> 2 <html lang="en"> 3<head> 4 <meta charset="UTF-8"> 5 <title>測試es5</title> 6 <style> 7 *{ 8 margin:0; 9 padding:0; 10 box-sizing: border-box; 11 } 12 #el{ 13 width: 100px; 14 height: 100px; 15 background-color: red; 16 } 17 </style> 18 </head> 19 <body> 20 <div id="el"></div> 21 <script> 22 var elementStyle = document.createElement(‘div‘).style 23 24 var vendor = (function(){ 25 let transformNames = { 26 webkit: ‘webkitTransform‘, 27 Moz: ‘MozTransform‘, 28 O: ‘OTransform‘, 29 ms: ‘msTransform‘, 30 standard: ‘transform‘ 31 } 32 33 for (let key in transformNames) { 34 if (elementStyle[transformNames[key]] !== undefined) { 35 return key 36 } 37 } 38 39 return false 40 })() 41 42 function prefixStyle(style) { 43 if (vendor === false) { 44 return false 45 } 46 47 if (vendor === ‘standard‘) { 48 return style 49 } 50 51 return vendor + style.charAt(0).toUpperCase() + style.substr(1) 52 } 53 document.getElementById(‘el‘).onmouseenter=function(){ 54 document.getElementById(‘el‘).style[prefixStyle(‘transform‘)] =‘scale(1.5)‘ 55 } 56 document.getElementById(‘el‘).onmouseleave=function(){ 57 document.getElementById(‘el‘).style[prefixStyle(‘transform‘)] =‘scale(1)‘ 58 } 59 60 </script> 61 </body> 62 </html>
es6的寫法
1 let elementStyle = document.createElement(‘div‘).style 2 3 let vendor = (() => { 4 let transformNames = { 5 webkit: ‘webkitTransform‘, 6 Moz: ‘MozTransform‘, 7 O: ‘OTransform‘, 8 ms: ‘msTransform‘, 9 standard: ‘transform‘ 10 } 11 12 for (let key in transformNames) { 13 if (elementStyle[transformNames[key]] !== undefined) { 14 return key 15 } 16 } 17 18 return false 19 })() 20 21 export function prefixStyle(style) { 22 if (vendor === false) { 23 return false 24 } 25 26 if (vendor === ‘standard‘) { 27 return style 28 } 29 30 return vendor + style.charAt(0).toUpperCase() + style.substr(1) 31 }
js修改css時如何考慮兼容性問題es5+es6