兼容requestAnimationFrame
let lastTime = 0
let vendors = ['ms', 'moz', 'webkit', 'o']
for (let x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']
window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame']
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function (callback, element) {
let currTime = new Date().getTime()
let timeToCall = Math.max(0, 16 - (currTime - lastTime))
let callbackParams = currTime + timeToCall
let id = window.setTimeout(() => { callback(callbackParams) }, timeToCall)
lastTime = currTime + timeToCall
return id
}
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function (id) {
clearTimeout(id)
}
}
兼容classList
if (!('classList' in document.documentElement)) {
Object.defineProperty(HTMLElement.prototype, 'classList', {
get: function () {
let self = this
function update (fn) {
return function (value) {
let classes = self.className.split(/s+/g)
let index = classes.indexOf(value)
fn(classes, index, value)
self.className = classes.join(' ')
}
}
return {
add: update(function (classes, index, value) {
if (!~index) classes.push(value)
}),
remove: update(function (classes, index) {
if (~index) classes.splice(index, 1)
}),
toggle: update(function (classes, index, value) {
if (~index) { classes.splice(index, 1) } else { classes.push(value) }
}),
contains: function (value) {
return !!~self.className.split(/s+/g).indexOf(value)
},
item: function (i) {
return self.className.split(/s+/g)[i] || null
}
}
}
})
}
兼容dataset
if (window.HTMLElement) {
if (Object.getOwnPropertyNames(HTMLElement.prototype).indexOf('dataset') === -1) {
Object.defineProperty(HTMLElement.prototype, 'dataset', {
get: function () {
let attributes = this.attributes // 獲取節點的所有屬性
let name = []
let value = [] // 定義兩個數組保存屬性名和屬性值
let obj = {} // 定義一個空對象
for (let i = 0; i < attributes.length; i++) { // 遍歷節點的所有屬性
if (attributes[i].nodeName.slice(0, 5) === 'data-') { // 如果屬性名的前面5個字符符合"data-"
// 取出屬性名的"data-"的后面的字符串放入name數組中
name.push(attributes[i].nodeName.slice(5))
// 取出對應的屬性值放入value數組中
value.push(attributes[i].nodeValue)
}
}
for (let j = 0; j < name.length; j++) { // 遍歷name和value數組
obj[name[j]] = value[j] // 將屬性名和屬性值保存到obj中
}
return obj // 返回對象
}
})
}
}
參考: iview在ie9及以上的兼容問題解決方案