適配不同分辨率的另一種思路:頁面縮放transform:scale(a,b) translate(x,y)

解決前端頁面適配不同分辨率的問題有很多方法,見仁見智,可以在html的head標簽里寫js代碼,在頁面加載之前判斷瀏覽器分辨率,選擇加載對應的css文件.也可以用css3的媒體查詢,寫在link標簽里引入不用css文件,還可以寫在css文件里,不再贅述,這里說一下另一個思路:頁面整體縮放.

效果

這種方法的思路是把整個頁面等比例縮放偏移,上下或者左右多出來的部分留白,所以不會在所有分辨率都適配的很完美,故而,有條件的還是用其他更完美的方法吧.


效果圖-左右留白

效果圖-上下留白

這種方法是頁面的整體縮放,里面的所有內(nèi)容都會縮放,包括字體,圖片等,所以排版布局不會變形.

代碼

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>數(shù)據(jù)資產(chǎn)展示頁面</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'));
  }
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容