自适应,顾名思义就是自动适应,用在网站建设中就是让页面自动适应不同大小的终端,包括智能手机、平板电脑和电脑显示器。现在网站在自适应已经在大范围的使用了,今天我们和大家一起讨论下Vue框架的自适应的实现方法和相关代码。
首先我们在配置文件设置大屏设计的尺寸1920*1080:
//appConfig.js export default{ screen:{ width:1920, height:1080, scale:20 }//大屏设计宽高 }
其次就是定义resetScreenSize.js
import appConfig from '../config/base' export function pageResize(callback) { let init = () => { console.log(window.innerHeight + "," + window.innerWidth); let _el = document.getElementById('app'); let hScale = window.innerHeight / appConfig.screen.height; let wScale = window.innerWidth / appConfig.screen.width; let pageH = window.innerHeight; let pageW = window.innerWidth; let isWider = (window.innerWidth / window.innerHeight) >= (appConfig.screen.width / appConfig.screen.height); console.log(isWider); if (isWider) { _el.style.height = window.innerHeight+'px';// '100%'; _el.style.width = pageH * appConfig.screen.width / appConfig.screen.height + 'px'; _el.style.top='0px'; _el.style.left=(window.innerWidth -pageH * appConfig.screen.width / appConfig.screen.height)*0.5+'px'; console.log(_el.style.width + "," + _el.style.height) } else { _el.style.width = window.innerWidth+'px';// '100%'; _el.style.height = pageW * appConfig.screen.height / appConfig.screen.width + 'px'; _el.style.top= 0.5*(window.innerHeight-pageW * appConfig.screen.height / appConfig.screen.width)+'px'; _el.style.left='0px'; console.log(_el.style.height); console.log(_el.style.top); } document.documentElement.style.fontSize = (_el.clientWidth / appConfig.screen.scale) + 'px'; } var resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize'; window.addEventListener(resizeEvt, init, false); document.documentElement.addEventListener('DOMContentLoaded', init, false); init() }
最后就是使用方法:
1、main.js 引入
import appConfig from './config/base.js'; Vue.prototype.appConfig=appConfig; app.Vue 在mounted函数引入 import {pageResize} from './utils/resetScreenSize' export default { name: 'App', data(){ return{ } }, mounted(){ pageResize(); console.log('pageResize'); } }
2、组件中样式lang="stylus"
.mc{ display :flex; flex-direction :column; align-content :center; justify-content :center; display: flex; flex: 1 1 auto; flex-direction: column; padding:(15/96)rem; } .leftC{ width :(410/96)rem; } .centerC{ width :(1060/96)rem; } .rightC{ width :(450/96)rem; }
注意:其中 96为 配置文件中1920/20得来,这样不用在进行各种换算了。
好的,以上代码就是我们现目前我们使用的在Vue框架自适应页面大小的代码,如果你有更好的方法可以和我们一起来讨论,如果你喜欢的话的记得收藏哦。
地址:绵阳市临园路东段78号B座13层
电话:0816-6339181
邮箱:kf@kf51.cn
微信公众号:
Copyright © 绵阳动力网站建设 www.kf51.cn All Rights Reserved 蜀ICP备08100083号