超过高宽比水平溢出遮挡,小于高宽比垂直溢出遮挡js动态计算位置实现

  function adjust() {
            var cw = 1920, ch = 1080;
            var h1 = 0,
            h2 = 0;
            if (document.documentElement && document.documentElement.clientHeight) {
                h1 = document.documentElement.clientHeight;
            }
            if (document.body) h2 = document.body.clientHeight;
            var h = Math.max(h1, h2);
            if (window.ActiveXObject) {
                h += 4;
            } else {
                h += 4;
            }
            var blh = h / ch;

            var w1 = 0,
            w2 = 0;
            if (document.documentElement && document.documentElement.clientWidth) {
                w1 = document.documentElement.clientWidth;
            }
            if (document.body) w2 = document.body.clientWidth;
            var w = Math.max(w1, w2);
            if (window.ActiveXObject) {
                w += 4;
            } else {
                w += 4;
            }
            var ow, oh;
            var blw = w / cw;
            var blwh = (w / h);
            var blcwh = (cw / ch);
            var woverflow = false;
            if (blwh > blcwh) {
                ow = w;
                oh = ch * blw;
                woverflow = true;
            } else {
                ow = cw * blh;
                oh = h;
            }

            ow = Math.round(ow);
            oh = Math.round(oh);
            var pic = document.getElementById('pic');
            pic.style.width = ow + "px";
            pic.style.height = oh + "px";
            var pt = Math.round(woverflow ? 0.5 * (h - oh) : 0);
            var wt = Math.round((w - ow) / 2);
            pic.style.top = pt + "px";
            pic.style.left = (woverflow ? 0 : wt) + "px";
            pic.style.right = (woverflow ? 0 : wt) + "px";
            pic.style.display = "block";
            var wp = document.getElementById('wp');
            var wpa = document.getElementById('wpa');
            wp.style.zoom = blh;
            wp.style.top = Math.round(((440 * (woverflow ? blw : blh)) + (woverflow ? pt : 0)) / blh) + "px";
            var wpt = Math.round((ow - 590 * blh) / 2 + (woverflow ? 0 : (w - ow) / 2))
            wp.style.left = wpt + "px";
            wp.style.right = wpt + "px";
            wp.style.display = "block";
            // alert(pt + '-' + woverflow + '-' + oh + '-' + blw + '-' + ow + '-' + cw + '-' + h + '-' + w);
        };

        adjust();

        window.onresize = function () {
            setTimeout(function () {
                adjust();
            },
            200)
        };
        

猜你喜欢

转载自blog.csdn.net/oshuangyue12/article/details/80695854