javascript的未知尺寸图片保持比例水平垂直居中函数

JavaScript的图片在容器内水平垂直居中的函数,利用图片加载获取图片大小,使之在父节点内水平垂直居中

展示方式有两种:

 1、当参数keepImageFull为true:保持图片比例,使图片可完整的水平居中显示在父节点内,未能填充的部分留白

 2、当参数keepImageFull为false: 保持图片比例,完全覆盖父节点,超出部分溢出

container_width和container_height函数不是必须的,仅当无法自动获取到图片父节点的尺寸时传入

容器内不想用此方法处理的函数的图片,可以在图片节点上加上data-skip-loader属性

使用实例:

<div id="container">
    <ul>
        <li><img src="1.png" alt=""></li>
        <li><img src="1.png" alt=""></li>
        <li><img src="1.png" alt=""></li>
        <li><img src="1.png" alt=""></li>
    </ul>
    <img src="" alt="" class="ignore-element" data-skip-loader="1">
</div>
<script>
    imageCenter(document.getElementById('container'), false, 300, 200);
</script>

 

具体看参数说明:

/**
 * 设置元素样式
 * @param {Array|Element} element 要设置样式的dom元素
 * @param {Object}        styles  样式属性集合
 */
function setStyle(element, styles) {
    var cssText = [];
    if (styles) {
        for (var prop in styles) {
            if (styles.hasOwnProperty(prop)) {
                cssText.push([prop, styles[prop]].join(':'));
            }
        }
    }

    if (cssText.length) {
        element.style.cssText += ';' + cssText.join(';');
    }

    return element;
}

/**
 * 图片预加载
 * @param  {Element}  node         要加载的容器节点
 * @param  {Function} after_single 单词加载成功执行函数
 * @param  {Function} after_all    <可选> 全部成功执行函数
 * @param  {Object}   context      <可选> 函数运行域
 */
function loadImage(node, after_single, after_all, context) {
    function load_check(loading) {
        if (loading["complete"]) {
            complete++;
            setStyle(loading.ele, {
                'width': 'auto',
                'max-width': 'none',
                'max-height': 'none'
            });
            if (typeof after_single === 'function') {
                after_single.call(context, loading.ele, loading.width || 1, loading.height || 1, loading.i);
            }
            if (complete == filter_images.length && typeof after_all === 'function') {
                after_all.call(context, complete);
            }
            loading.ele = null;
            loading = null;
        } else {
            setTimeout(function(){
                load_check(loading);
            }, 100);
        }
    }
    node = node || document;

    var images = node.getElementsByTagName("img");
    var complete = 0;
    // 过滤
    var filter_images = [];
    for (var j = 0; j < images.length; j++) {
        if (!images[j].hasAttribute('data-skip-loader')) {
            filter_images.push(images[j]);
        }
    }

    var i = 0;
    while(i < filter_images.length) {
        var image = filter_images[i];
        var loading = new Image();
        setStyle(image, {
            'width': '100%',
            'height': 'auto',
            'max-width': '100%',
            'max-height': '100%'
        });
        loading.src = image.src;
        loading.ele = image;
        loading.i = i;
        load_check(loading);
        loading = null;
        i++;
    }
}

/**
 * 图片水平垂直居中于容器中
 * @param  {Element} node              容器节点
 * @param  {Boolean} keepImageFull     保持图片全图可见,未能填充的部分留白 || 以长宽的最小值填满,未能显示的部分溢出影藏
 * @param  {Number}  container_width   <可选> 容器宽度
 * @param  {Number}  container_height  <可选> 容器高度
 */
function imageCenter(node, keepImageFull, container_width, container_height) {
    loadImage(node, function(img, width, height, index) {
        var parent = img.parentNode;
        if (!container_width) {
            container_width = Math.max(1, parent.offsetWidth);
        }
        if (!container_height) {
            container_height = Math.max(1, parent.offsetHeight);
        }
        setStyle(parent, {
            'overflow': 'hidden'
        });
        var css = {
            'display': 'block',
            'border-width': 0
        };
        css['width'] = Math.max(1, Math.min(width, container_width));
        css['height'] = css["width"] * height / width;

        keepImageFull = keepImageFull ? 1 : -1;

        // 宽度修正
        if ((css['width'] - Math.min(width, container_width)) * keepImageFull > 0) {
            css['width'] = container_width;
            css['height'] = height * container_width / width;
        }

        // 高度修正
        if ((css['height'] - Math.min(height, container_height)) * keepImageFull > 0)  {
            css['width'] = width * container_height / height;
            css['height'] = container_height;
        }


        css['margin-left'] = (container_width - css['width']) / 2 + 'px';
        css['margin-top'] = (container_height - css['height']) / 2 + 'px';
        css['width'] += 'px';
        css['height'] += 'px';

        setStyle(img, css);
    });
}

 

posted on 2015-12-29 11:51  坚壳  阅读(426)  评论(1编辑  收藏  举报