koel/resources/assets/js/utils/$.js

54 lines
1.1 KiB
JavaScript
Raw Normal View History

2016-12-21 03:30:22 +00:00
/**
* A utility that aims to replace jQuery for the most basic DOM methods.
* @type {Object}
*/
2016-12-20 15:44:47 +00:00
export const $ = {
is (el, selector) {
return (el.matches ||
el.matchesSelector ||
el.msMatchesSelector ||
el.mozMatchesSelector ||
el.webkitMatchesSelector ||
el.oMatchesSelector).call(el, selector)
},
addClass (el, className) {
if (!el) {
return
}
if (el.classList) {
el.classList.add(className)
} else {
el.className += ` ${className}`
}
},
removeClass (el, className) {
if (!el) {
return
}
if (el.classList) {
el.classList.remove(className)
} else {
el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ')
}
},
scrollTo (el, to, duration) {
if (duration <= 0 || !el) {
return
}
const difference = to - el.scrollTop
const perTick = difference / duration * 10
window.setTimeout(() => {
el.scrollTop = el.scrollTop + perTick
if (el.scrollTop === to) {
return
}
2016-12-20 16:02:58 +00:00
this.scrollTo(el, to, duration - 10)
2016-12-20 15:44:47 +00:00
}, 10)
}
}