繁体   English   中英

如何以跨浏览器的方式设置页面中图像的最大宽度?

[英]How can I set the max width for images in a page in a cross-browser way?

如何使用CSS或Javascript以跨浏览器的方式设置页面中图像的最大宽度?

img.limitsize { max-width: 640px; }

适用于所有现代浏览器。 在IE6上不起作用。 如果需要IE6支持,则必须使用JS,例如:

// IE-6-only function to implement max-width
// (you can do min- and height similarly)
//
function MaxWidthFix(element) {
    var width= element.currentStyle['max-width'];

    function update() {
        element.style.width= width;
        var wmax= element.offsetWidth;
        element.style.width= 'auto';
        var wauto= element.offsetWidth;
        if (wauto>wmax)
            element.style.width= width;
    }

    // If width or max-width is set in % or em, window and font resizes
    // might change sizes, requiring an update
    //
    window.attachEvent('onresize', update);
    setTimeout(update, 1000);
    update();
}

if (!('maxWidth' in document.body.style)) {
    var imgs= document.getElementsByTagName('img');
    for (var i= imgs.length; i-->0;)
        if (imgs[i].className.indexOf('limitsize')!==-1)
           MaxWidthFix(imgs[i]);
}

在CSS中使用

img {width:400px;}

但是请使用您自己的尺寸。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM