一种前端大屏适配方案
2026/7/24 1:55:10 网站建设 项目流程

前端开发过程中,屏幕适配是个常见问题。在前端大屏可视化项目中,屏幕适配技术是保障设计稿与实际显示效果一致性的核心技术环节。适配方案目前主要有视口缩放、相对单位、响应式布局等,本文主要介绍如何使用 CSS3变换缩放技术,实现大屏应用的自适应适配方案。

在开发大屏适配过程中,有两个尺寸,一个是设计稿的尺寸,一个是屏幕尺寸,我们需要做的就是,在不同屏幕尺寸下,我们的页面都能够按照原比例全部显示出来。如下图:

首先我们要想的问题是,页面缩放的比例,宽度缩放的比例是屏幕宽度/设计稿宽度,高度缩放比例是屏幕高度/设计稿高度。有个缩放比例后,就把整个页面按照较小的比例缩放就可以了。

const scaleX = innerWidth / width; // width是设计稿宽度 const scaleY = innerHeight / height; // height是设计稿高度 el.style.transform = `scale(${Math.min(scaleX, scaleY)})`;

但是这时会有小问题,页面缩放的中心位置不对,我们需要设置一下transformOrigin

el.style.transformOrigin = 'top left'; const scaleX = innerWidth / width; const scaleY = innerHeight / height; el.style.transform = `scale(${Math.min(scaleX, scaleY)})`;

到这里大屏适配的基本逻辑已经写好了,我们需要封装一个函数,然后在屏幕变化时,调用该函数,进行各种屏幕的适配。

function autoScale(selector, options) { const el = document.querySelector(selector); const { width, height } = options; // 传入设计稿的宽和高 el.style.transformOrigin = 'top left'; function init() { const scaleX = innerWidth / width; const scaleY = innerHeight / height; el.style.transform = `scale(${Math.min(scaleX, scaleY)})`; } init(); addEventListener('resize', init); }

这时,页面基本可以等比例缩放显示了,但是,页面内容在屏幕的左上,没有居中显示。还需要再优化一下。可以通过移动X和Y的移动来让页面一直显示在中间。注意:transform时,要先写translate,再scale,不然会发现不对。

function autoScale(selector, options) { const el = document.querySelector(selector); const { width, height } = options; el.style.transformOrigin = "top left"; function init() { const scaleX = innerWidth / width; const scaleY = innerHeight / height; const left = (innerWidth - width * Math.min(scaleX, scaleY)) / 2; const top = (innerHeight - height * Math.min(scaleX, scaleY)) / 2; el.style.transform = `translate(${left}px, ${top}px) scale(${Math.min(scaleX, scaleY)})`; } init(); addEventListener("resize", init); }

这时大屏适配方案基本完成,为了体验更丝滑,还需要再进一步优化:因为resize事件是个触发频率比较高的事件,所以需要加一个防抖,然后会发现每一次resize页面变化得比较生硬,所以还要加一个过渡的效果。

function autoScale(selector, options) { const el = document.querySelector(selector); const { width, height } = options; el.style.transformOrigin = "top left"; el.style.transtion = 'transform .5s' function init() { const scaleX = innerWidth / width; const scaleY = innerHeight / height; const left = (innerWidth - width * Math.min(scaleX, scaleY)) / 2; const top = (innerHeight - height * Math.min(scaleX, scaleY)) / 2; el.style.transform = `translate(${left}px, ${top}px) scale(${Math.min(scaleX, scaleY)})`; } init(); addEventListener("resize", debounce(init));

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询