Skip to content

Instantly share code, notes, and snippets.

@aprilandjan
Last active November 30, 2016 15:22
Show Gist options
  • Save aprilandjan/7908bed9c8f099a0df983f400a5f8f91 to your computer and use it in GitHub Desktop.
Save aprilandjan/7908bed9c8f099a0df983f400a5f8f91 to your computer and use it in GitHub Desktop.
// 带有一个px作为单位
var rem = {
px: 1
};
var _timeoutId = 0
var _timeout = 0
var _resizeCallbacks = []
var _maxPx
rem.init = function(dw, maxPx){
dw = dw || 640;
_maxPx = maxPx || 0.8
var doResize = function () {
var vw = window.innerWidth;
rem.px = vw / dw;
if(rem.px > _maxPx) {
rem.px = _maxPx
}
document.querySelector('html').style.fontSize = 100 * rem.px + 'px';
_timeoutId = 0
_resizeCallbacks.forEach((cb) => {
cb.callback.call(cb.scope)
})
};
doResize();
window.addEventListener('resize', function () {
if(_timeoutId) {
window.clearTimeout(_timeoutId);
}
_timeoutId = window.setTimeout(doResize, _timeout)
});
};
rem.registerResize = function(callback, scope) {
for(var cb of _resizeCallbacks) {
if(cb.callback == callback || cb.scope == scope){
return;
}
}
_resizeCallbacks.push({
callback: callback,
scope: scope
})
}
rem.unregisterResize = function(callback, scope) {
for(var cb of _resizeCallbacks) {
if(cb.callback == callback || cb.scope == scope){
_resizeCallbacks.splice(_resizeCallbacks.indexOf(cb), 1)
}
}
}
// 导出 rem
export default rem;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment