解决前端页面适配不同分辨率的问题有很多方法,见仁见智,可以在html的head标签里写js代码,在页面加载之前判断浏览器分辨率,选择加载对应的css文件.也可以用css3的媒体查询,写在link标签里引入不用css文件,还可以写在css文件里,不再赘述,这里说一下另一个思路:页面整体缩放.
效果
这种方法的思路是把整个页面等比例缩放偏移,上下或者左右多出来的部分留白,所以不会在所有分辨率都适配的很完美,故而,有条件的还是用其他更完美的方法吧.
这种方法是页面的整体缩放,里面的所有内容都会缩放,包括字体,图片等,所以排版布局不会变形.
代码
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="shortcut icon" href="./img/logo.ico" type="image/x-icon" />
<link rel="stylesheet" href="./css/index.css">
<title>数据资产展示页面</title>
</head>
<body>
<div id="container">
...
</div>
</body>
</html>
css
html {
padding: 0;
margin: 0;
}
body{
overflow: hidden;
background: #ccc;
height: 100vh;
}
#container {
margin: 0 auto;
box-sizing: border-box;
background: url(../img/bj.jpg) no-repeat;
background-size: 100% 100%;
overflow: hidden;
transform-origin: left top;
transition: transform 0.2s
}
js
screenScale($('#container'));
function screenScale(element) {
let width = '1920';
let height = '1080';
let offsetWidth = window.innerWidth;
let offsetHeight = window.innerHeight;
let top = 0;
let left = 0;
let scaleX = offsetWidth / width;
let scaleY = offsetHeight / height;
let scale = Math.min(scaleX, scaleY);
top = (offsetHeight - height * scale) / 2;
left = (offsetWidth - width * scale) / 2;
//核心代码
const transform = `translate(${left}px, ${top}px) scale(${scale})`;
element.width(width);
element.height(height);
element.css({'transform': transform});
}
window.onresize = function () {
screenScale($('#container'));
}