当前位置: 首页 > 科技观察

构建一个从0到1的页面自适应组件(Vue.js)

时间:2023-03-23 10:38:57 科技观察

#full-screen-container{position:fixed;top:0px;left:0px;overflow:hidden;transform-origin:lefttop;z-index:999;组件会根据屏幕比例和当前浏览器窗口大小自动缩放。组件中推荐使用百分比和flex进行布局,以获得不同分辨率下更一致的显示效果。使用前请注意将body的边距设置为0,否则会造成计算错误。fullScreenContainer.vue

#full-screen-container{position:fixed;top:0px;left:0px;overflow:hidden;transform-origin:lefttop;z-index:999;autoResize.jsexportdefault{data(){return{dom:'',width:0,height:0,debounceInitWHFun:'',domObserver:''};},方法:{debounce(延迟,回调){letlastTime;returnfunction(){clearTimeout(lastTime);const[that,args]=[this,arguments];lastTime=setTimeout(()=>{callback.apply(that,args);},delay);};},observerDomResize(dom,callback){constMutationObserver=window.MutationObserver||window.WebKitMutationObserver||window.MozMutationObserver;constobserver=newMutationObserver(回调);observer.observe(dom,{attributes:true,attributeFilter:['style'],attributeOldValue:true});returnobserver;},asyncautoResizeMixinInit(){const{initWH,getDebounceInitWHFun,bindDomResizeCallback,afterAutoResizeMixinInit}=this;waitinitWH(false);getDebounceInitWHFun();bindDomResizeCallback();if(typeofafterAutoResizeMixinInit==='function')afterAutoResizeMixinInit();},initWH(resize=true){const{$nextTick,$refs,ref,onResize}=this;returnnewPromise(resolve=>{$nextTick(()=>{constdom=(this.dom=$refs[ref]);this.width=dom?dom.clientWidth:0;this.height=dom?dom.clientHeight:0;if(!dom){console.warn('DataV:Failedtogetdomnode,componentrenderingmaybeabnormal!');}elseif(!this.width||!this.height){console.warn('DataV:Componentwidthorheightis0px,renderingabnormalitymayoccur!');}if(typeofonResize==='function'&&resize)onResize();resolve();});});},getDebounceInitWHFun(){const{initWH}=this;this.debounceInitWHFun=this.debounce(100,initWH);},bindDomResizeCallback(){const{dom,debounceInitWHFun}=this;this.domObserver=this.observerDomResize(dom,debounceInitWHFun);window.addEventListener('resize',debounceInitWHFun);},unbindDomResizeCallback(){让{domObserver,debounceInitWHFun}=this;if(!domObserver)return;domObserver.disconnect();domObserver.takeRecords();domObserver=null;window.removeEventListener('resize',debounceInitWHFun);}},mounted(){const{autoResizeMixinInit}=this;autoResizeMixinInit();},beforeDestroy(){const{unbindDomResizeCallback}=this;unbindDomResizeCallback();}};这样就这样搭建了一个页面自适应组件。接下来引入组件看看效果"/>
效果很好,使得为某些人开发自适应页面变得非常容易。

最新推荐
猜你喜欢