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元素即可适配。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李泽举

如对你有帮助,那我就没白写

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值