900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > Vue自定义指令—解决H5页面不同尺寸屏幕的适配问题

Vue自定义指令—解决H5页面不同尺寸屏幕的适配问题

时间:2019-12-31 20:20:23

相关推荐

Vue自定义指令—解决H5页面不同尺寸屏幕的适配问题

基于vue框架针对H5在不同分辨率的手机做出来一套适配方案,具体如下:

设计图按iPhone6/7/8 去掉底部返回条的尺寸设计的: width:750px , height:1108px(可使用该方法应对其他设计图尺寸)

一、以设计图的尺寸为标注的做一套适配方案,就是出完美高度比:

function getResheightAndWidth() {//设计尺寸 w:750 h:1108//1.计算屏幕实际尺寸width / 设计图宽度比 750 宽度比;//2.通过比例算出高度应该是多少时,是完美比例//3.计算出实际高度与完美高度 的比例let adpter_scale = 1;let screen_width = document.body.clientWidth; //屏幕实际宽度let screen_height = document.body.clientHeight; //屏幕实际高度let w_scale = screen_width / 750; //计算屏幕实际尺寸width / 设计图宽度比 750 宽度比;let compute_height = 1108 * w_scale; //通过比例算出高度应该是多少时,是完美比例adpter_scale =parseInt((screen_height / compute_height)*100)/100; //计算出实际高度与完美高度 的比例return adpter_scale;}

二、在app.vue中添加自定指令:

//自定义样式指令let adpter_scale = getResheightAndWidth();//计算出来的完美宽高比console.log(adpter_scale)Vue.directive('margin', {//margin 上,右,下,左bind: function (el, binding, vnode) {let value = binding.expression.split(',');if(+value[0]) el.style.marginTop = +value[0] * adpter_scale + 'rem';if(+value[1]) el.style.marginRight = +value[1] * adpter_scale + 'rem';if(+value[2]) el.style.marginBottom = +value[2] * adpter_scale + 'rem';if(+value[3]) el.style.marginLeft = +value[3] * adpter_scale + 'rem';}})Vue.directive('padding', {//padding 上,右,下,左bind: function (el, binding, vnode) {let value = binding.expression.split(',');if(+value[0]) el.style.paddingTop = +value[0] * adpter_scale + 'rem';if(+value[1]) el.style.paddingRight = +value[1] * adpter_scale + 'rem';if(+value[2]) el.style.paddingBottom = +value[2] * adpter_scale + 'rem';if(+value[3]) el.style.paddingLeft = +value[3] * adpter_scale + 'rem';}})Vue.directive('height', {//高度bind: function (el, binding, vnode) {let value = +binding.value;if(value) el.style.height = value * adpter_scale + 'rem';}})Vue.directive('width', {//宽度bind: function (el, binding, vnode) {let value = +binding.value;if(value) el.style.width = value * adpter_scale + 'rem';}})Vue.directive('line-height', {//行高bind: function (el, binding, vnode) {let value = +binding.value;if(value) el.style.lineHeight = value * adpter_scale + 'rem';}})

自定义指令只列举出了常用margin/padding/width/height/line-height,如果需要font-size等其他css适配样式,可自行添加。

三、在组件中的使用:

在需要适配的dom元素上添加自定义指令:margin , padding 四个参数都是 (上,右,下,左) 用逗号隔开,不适配传0就可以了

<button v-margin="1.4,0,0,2.2" v-padding="2,0,1,4.2" v-height="2.3" v-width="9.7" v-line-height="2" class="btn blue" >按钮</button>

传入的参数都是按标准设计尺寸传入,通过在高度比换算之后,dom元素即可适配。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。