每次重复兼容性获取,且做判断处理
function getCss(element,attr) {
if ('getComputedStyle' in window) {
return window.getComputedStyle(element)[attr]
}
return element.currentStyle[attr]
}
var body = document.body
console.log(getCss(body,'height'))
console.log(getCss(body,'margin'))
console.log(getCss(body, 'background'))
减少重复兼容性获取
var flag = 'getComputedStyle' in window
function getCss(element, attr) {
if (flag) {
return window.getComputedStyle(element)[attr]
}
return element.currentStyle[attr]
}
var body = document.body
console.log(getCss(body, 'height'))
console.log(getCss(body, 'margin'))
console.log(getCss(body, 'background'))
重构函数,减少重复兼容性获取,和判断
function getCss(element, attr) {
if ('getComputedStyle' in window) {
getCss = function getCss(element, attr) {
return window.getComputedStyle(element)[attr]
}
} else {
getCss = function getCss(element, attr) {
return element.currentStyle[attr]
}
}
return getCss(element, attr)
}
var body = document.body
console.log(getCss(body, 'height'))
console.log(getCss(body, 'margin'))
console.log(getCss(body, 'background'))