还是 js 替代 vw vh 了

有个需求是要层叠两张图,就像你现在看到的:整个浏览器和html页面,内层图片要水平居中,等比例与源UI图适配不同设备

本来很简单的使用 vw vh了(

核心代码

            top: 13.25vh;
            left: 50%;
            margin-left: -32.31vw;
            width: 64.62vw;
            height: 61.56vh;

),但是发觉不太居中,而且考虑到移植的兼容性,还是用jq搞了一遍:

        (function () {
            var size = {
                uiImage: [530, 830],
                widthHeight: [340, 510],
                leftTop: [94, 110]
            };
            $('.top').css(getCss(size));
            function getCss(sizeSrc) {
                function ratio(arrTop, arrBottom) {
                    var arr = [];
                    for (var i = 0, j = arrTop.length; i < j; i++) {
                        arr[i] = arrTop[i] / arrBottom[i];
                    }
                    return arr;
                }
                var realSize, ratios, outSize, outLeftTop, ops;
                realSize = [$(window).width(), $(window).height()];
                ratios = ratio(sizeSrc.uiImage, realSize);
                outSize = ratio(sizeSrc.widthHeight, ratios);
                outLeftTop = ratio(sizeSrc.leftTop, ratios);
                ops = {
                    width: outSize[0],
                    height: outSize[1],
                    left: outLeftTop[0],
                    top: outLeftTop[1]
                };
                return ops;
            }
        }())

考虑到不想再新建一个js文件,再次包装下:

<div class="top-image" ui-image="530,830" width-height="340,510" left-top="94,110" ></div>
 
(function () {
  var obj = $('.top-image');
  obj.css(getCss({
    uiImage: obj.attr('ui-image').split(','),
    widthHeight: obj.attr('width-height').split(','),
    leftTop: obj.attr('left-top').split(',')
  }));
  function getCss(sizeSrc) {
    function ratio(arrTop, arrBottom) {
      var arr = [];
      for (var i = 0, j = arrTop.length; i < j; i++) {
        arr[i] = arrTop[i] / arrBottom[i];
      }
      return arr;
    }
    var realSize, ratios, outSize, outLeftTop, ops;
    realSize = [$(window).width(), $(window).height()];
    ratios = ratio(sizeSrc.uiImage, realSize);
    outSize = ratio(sizeSrc.widthHeight, ratios);
    outLeftTop = ratio(sizeSrc.leftTop, ratios);
    ops = {
      width: outSize[0],
      height: outSize[1],
      left: outLeftTop[0],
      top: outLeftTop[1]
    };
    return ops;
  }
}())
上一篇:Swift:playground


下一篇:JS它DOM