vue可视化大屏使用css3的缩放transform: scale(X)属性适配
想必近几年前端的数据可视化越来越重要了,很多甲方爸爸都喜欢那种炫酷的大屏幕设计,类似如下这种:
遇到的这样的项目,大多是同学想到的是用echarts或chart.js,再搭配各种mvvm框架(vue),找二次封装过的组件,然后开始埋头开始写了,写着写着你会发现,如何适配不同屏幕呢?css媒体查询吧,用vw吧,哪个好点呢。其实写到最后,我觉得都不好对于这种拿不定主意的情况呢,最好还是参考大厂的做法,于是去找了网易有数,百度suger等,仔细观察他们都采用了css3的缩放transform: scale(X)
属性,看到这是不是有种豁然开朗的感觉
于是我们只要监听浏览器的窗口大小,然后控制变化的比例就好了,他们是如何写这样的页面的:
在components目录下创建ScaleBox.vue文件
<template> <div ref="ScaleBox" :style="{ width: width + 'px', height: height + 'px', }" > <slot></slot> </div> </template> <script> export default { name: "ScaleBox", props: { }, data() { return { scale: "", width:1920, height:937 }; }, mounted() { this.setScale(); window.addEventListener("resize", this.debounce(this.setScale, 100)); }, methods: { getScale() { let { width, height } = this; let wh = window.innerHeight / height; let ww = window.innerWidth / width; console.log(ww < wh ? ww : wh); return ww < wh ? ww : wh; }, setScale() { if(window.innerHeight ==1080){ this.height = 1080 }else{ this.height = 937 } this.scale = this.getScale(); if (this.$refs.ScaleBox) { this.$refs.ScaleBox.style.setProperty("--scale", this.scale); } }, debounce(fn, delay) { let delays = delay || 500; let timer; return function () { let th = this; let args = arguments; if (timer) { clearTimeout(timer); } timer = setTimeout(function () { timer = null; fn.apply(th, args); }, delays); }; }, }, }; </script> <style> #ScaleBox { --scale: 1; } .ScaleBox { position: absolute; transform: scale(var(--scale)) translate(-50%, -50%); display: flex; flex-direction: column; transform-origin: 0 0; left: 50%; top: 50%; transition: 0.3s; z-index: 999; } </style> 复制代码
页面引用,把大屏首页布局放入ScaleBox组件内,就可以愉快的运用px或%布局了
import ScaleBox from '@/components/ScaleBox.vue' <ScaleBox >内容</ScaleBox > 复制代码
只要把页面放在这个组件中,就能实现跟大厂们类似的效果。这种方式下不管屏幕有多大,分辨率有多高,只要屏幕的比例跟你定的比例一致,都能呈现出完美效果。而且开发过程中,样式的单位也可以直接用px,省去了转换的烦恼~~~
作者:夏末_阳光依然耀眼
链接:https://juejin.cn/post/7026602801262231582